如何在javascript中替换数组中的字符串之间的空格

时间:2018-01-09 10:09:31

标签: javascript arrays

我有一个数组如下

## UBUNTU-LIKE ##
sudo apt-get install libglu1-mesa:i386
## Fedora ##
dnf install mesa-libGLU.i686

我想用下划线替换字符串元素之间的空格。 我的预期输出是

 [ 'category','book id','author book','book 
    title','price','publication','publication date' ]

4 个答案:

答案 0 :(得分:1)

array#mapstring#replace

一起使用



var data = [ 'category','book id','author book','book title','price','publication','publication date' ],
    result = data.map(word => word.replace(' ', '_'));
console.log(result);




答案 1 :(得分:0)

let input = [ 'category','book id','author book','book title','price','publication','publication date' ]

let output = input.map( word => word.replace(" ","_") )

// Or for ALL spaces in string : .replace(/ /g, "_")

答案 2 :(得分:0)

newArray = oldArray.map(elem => elem.replace(" ", "_"));

答案 3 :(得分:0)

var arr =  [ 'category','book_id','author_book',
    'book_title','price','publication','publication_date' ];
    
    arr = arr.map(function(data){
       if(data.split(" ").length>1){
          data.join("_")
       }
     return data;
       
    
    })

   console.log(arr)