-1

i have an array as follows

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

i want to replace space between the string elements with underscore. My expected output is

  [ 'category','book_id','author_book',
    'book_title','price','publication','publication_date' ]
Anuja vinod
  • 99
  • 3
  • 11

4 Answers4

1

Use array#map with string#replace

var data = [ 'category','book id','author book','book title','price','publication','publication date' ],
    result = data.map(word => word.replace(' ', '_'));
console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
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, "_")
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
0
newArray = oldArray.map(elem => elem.replace(" ", "_"));
Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
Pac0
  • 21,465
  • 8
  • 65
  • 74
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)
Ved
  • 11,837
  • 5
  • 42
  • 60