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>';
我想用破折号替换标题中的空格。
尝试使用title.replace(/\s/g , "-")
代替。(/\s/
是空格的正则表达式转义符)。
此外,执行以下操作:
title = title.replace(/\s/g , "-");
var html = "<div>" + title + "</div>";
// ...
我发现在替换函数中普遍使用的正则表达式很难阅读 - 而且很容易忘记不要引用你要搜索的字符串,或者省略/g以表示全局替换。对于简单地将空格替换为破折号之类的操作,使用更易于理解的“split”和“join”同样快速。
alert("this is a test".split(" ").join("-"));
title.replace
不会改变 title 变量,但会返回一个值已被替换的字符串。你需要使用返回的值:var html = "<div>"+title+"<br/>";
var newTitle = document.write(title.replace(/ /g,"-"));
html+= '<p><a href="go.aspx?title=' + newTitle + '">Details<\/a></p></div>';
var str = "Tatwerat Development Team";
str = str.replace(/\s+/g, '-');
document.write(str)
ehdv的回答让你接近90%。我只是想澄清他建议的代码应该放在你的代码中的位置,而且它不应该出现在注释中。
var html = "<div>" + title + "<br/>";
title = title.replace(/\s/g , "-");
html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p></div>';
var html = "<div>" + title + "<br/>";
title = title.replace(/\s+/g , "-");
html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p>
var html = "<div>" + title + "</div>";
title = title.replace(/\s/g , "-");
html+= '<p><a href="go.aspx?title=' + title + '">Details</a></p>
title.replace(' ', '-')
- ma11hew28