Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace space with dash JavaScript

Tags:

javascript

var html = "<div>"+title+"<br/>";
document.write(title.replace(/ /g,"-"));
html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p></div>';

I want to replace title space with dash.

like image 617
ruru Avatar asked Apr 17 '10 05:04

ruru


2 Answers

I find regex expressions commonly used in the replace function very hard to read - plus it's easy to forget to not quote the string you are searching for or to omit the /g to indicate a global replace. For doing something simple like replacing a space with a dash, using an easier to understand "split" followed by a "join" is just as fast.

alert("this is a test".split(" ").join("-"));

https://jsfiddle.net/n0u3aw5c/

like image 199
River Avatar answered Nov 07 '22 09:11

River


Try title.replace(/\s/g , "-") instead. (/\s/ is the regex escape for whitespace).

Also, do:

title = title.replace(/\s/g , "-");
var html = "<div>" + title + "</div>";
// ...
like image 39
ehdv Avatar answered Nov 07 '22 08:11

ehdv