关于字符串:在javascript中用下划线替换空格?

Replacing spaces with underscores in JavaScript?

我试图用这段代码替换空格,它适用于字符串中的第一个空格,但所有其他空格实例都保持不变。有人知道为什么吗?

1
2
3
4
5
6
function updateKey()
{
    var key=$("#title").val();
    key=key.replace("","_");
    $("#url_key").val(key);
}

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

编辑:或如果您不喜欢RES,则选择.split(' ').join('_')

编辑: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. (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.)


试试这个:

1
key=key.replace(/ /g,"_");

这将进行全局查找/替换

javascript替换


要回答Prasanna的以下问题:

How do you replace multiple spaces by
single space in Javascript ?

您可以使用相同的函数replace和不同的正则表达式。空白的表达式是\s,而"1次或多次"的表达式是+的加号,因此您只需将adam的答案替换为以下内容:

1
key=key.replace(/\s+/g,"_");

你可以试试这个

1
2
 var str = 'hello     world  !!';
 str = str.replace(/\s+/g, '-');

它甚至会用一个"-"替换多个空格。


我为它创建了JS性能测试http://jspef.com/split-and-join-vs-replace2


用下划线替换空格

1
2
var str = 'How are you';
var replaced = str.split(' ').join('_');

输出:你好吗?


我知道这是旧的,但我没有看到任何人提到延长字符串prototype

1
2
3
4
String.prototype.replaceAll = function(search, replace){
    if(!search || !replace){return this;} //if search entry or replace entry empty return the string
    return this.replace(new RegExp('[' + search + ']', 'g'), replace); //global RegEx search for all instances ("g") of your search entry and replace them all.
};


var text='你好世界';

new_text=text.replace('','');

console.log(新文本);