Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中用下划线替换空格?(Replacing spaces with underscores in JavaScript?)

I'm trying to use this code to replace spaces with _, it works for the first space in the string but all the other instances of spaces remain unchanged.(我正在尝试使用此代码用_替换空格,它适用于字符串中的第一个空格,但所有其他空格实例保持不变。)

Anybody know why?(谁知道为什么?) function updateKey() { var key=$("#title").val(); key=key.replace(" ","_"); $("#url_key").val(key); }   ask by Click Upvote translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try .replace(/ /g,"_");(试试.replace(/ /g,"_");)

Edit : or .split(' ').join('_') if you have an aversion to REs(编辑 :或.split(' ').join('_')如果您厌恶RE) Edit : John Resig said :(编辑John Resig说 :) If you're searching and replacing through a string with a static search and a static replace it's faster to perform the action with .split("match").join("replace") - which seems counter-intuitive but it manages to work that way in most modern browsers.(如果您正在搜索并通过静态搜索替换字符串并使用静态替换,则使用.split(“匹配”)执行操作的速度更快.join(“replace”) - 这看似违反直觉,但它设法工作这种方式在大多数现代浏览器中) (There are changes going in place to grossly improve the performance of .replace(/match/g, "replace") in the next version of Firefox - so the previous statement won't be the case for long.)((在下一版本的Firefox中,有一些变化可以大大提高.replace(/ match / g,“replace”)的性能 - 所以之前的声明不会长久。))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...