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"
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"
 
    
     
    
    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
 
    
    try this for multiple space
str.replace(/\s+/g,'_');
or single space
str.replace(/\s/g,'_');
 
    
    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.
