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

function updateKey()
{
    var key=$("#title").val();
    key=key.replace(" ","_");
    $("#url_key").val(key);
}

当前回答

我知道这是旧的,但我没有看到任何人提到扩展字符串原型。

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.
};

其他回答

我知道这是旧的,但我没有看到任何人提到扩展字符串原型。

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 str = 'hello     world  !!';
 str = str.replace(/\s+/g, '-');

它甚至会用单个的“-”替换多个空格。

下面来回答Prasanna的问题:

如何替换多个空格 Javascript中的单一空格?

您可以使用相同的函数替换为不同的正则表达式。空格的表达式是\s,而“1次或多次”的表达式是+加号,所以你只需将Adam的答案替换为以下内容:

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

只需使用replace: var text = 'Hello World'; New_text = text。Replace (' ', '_'); console.log (new_text);

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