1

I don't want to use split or join.

var str = "cause variety of files";  
alert(str.replace(" " , "_"));

The code above outputs : "cause_variety of files"

The output I seek is : "cause_variety_of_files"

War10ck
  • 12,060
  • 7
  • 40
  • 51
Sudharsan S
  • 15,058
  • 3
  • 28
  • 49

3 Answers3

3

Try this code :

str.replace(/ /g, "_");

By default, the replace function replace the first occurence. So you must use a RegExp with the global flag.

You can learn more on regulars expressions here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Magus
  • 14,245
  • 3
  • 37
  • 48
0

try this for multiple space

str.replace(/\s+/g,'_');

or single space

str.replace(/\s/g,'_');
Man Programmer
  • 5,150
  • 2
  • 17
  • 18
  • 3
    `Try this` does not teach the asker anything. Please explain what you did and why it should work, otherwise it's not a good answer. – Sterling Archer May 19 '14 at 14:38
0

Try using regular expression and the replace() function:

$(document).ready(function() {
    var elem = "cause variety of files";
    console.log(elem.replace(/\s+/g, '_'));
});

The regex takes all the whitespace ( 1 or more ) using the \s+ pattern and replace it by a string you like. In your case a underscore.

Mivaweb
  • 5,365
  • 3
  • 24
  • 51
  • 1
    You shouldn't use `alert()` like a debug statement. `console.log()` should be used for debugging (also because you can use breakpoints in dev tools if you need to pause execution). Also please explain what your regex does – Sterling Archer May 19 '14 at 14:39