开发者

replace space with dash JavaScript

开发者 https://www.devze.com 2022-12-27 18:18 出处:网络
var html = \"<div>\"+title+\"<br/>\"; document.write(title.replace(/ /g,\"-\")); html+= \'<p><a href=\"go.aspx?title=\' + title + \'\">Details<\\/a></p></div>
var html = "<div>"+title+"<br/>";
document.write(title.replace(/ /g,"-"));
html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p></div>';

I w开发者_JS百科ant to replace title space with dash.


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>";
// ...


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/


Calling title.replace will not change title, but return a string where the values have been replaced. You need to use the returned value:

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

The regular expression is fine, but will only replace spaces and not all whitespace.


var str = "Tatwerat Development Team";
str = str.replace(/\s+/g, '-');
document.write(str)


ehdv's answer gets you 90% of the way there. I just wanted to clarify where the code he suggested would go within your code, and it wouldn't look right in a comment.

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

This assumes that you DON'T want dashes in the div, but you DO in the URL.

And if you also want to replace multiple spaces that come immediately one after another with a SINGLE dash instead of ending up with double dashes in your title, use this instead:

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

I'd also like to mention that you're not closing your div. Maybe you just didn't include that part of your code but it's worth mentioning. There's also an unnecessary \ in your string. It's not hurting anything, but it's not needed. Maybe your code is meant to look like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消