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

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

当前回答

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

其他回答

用下划线替换空格

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

输出:How_are_you

替换所有事件

之所以会出现这种情况,是因为replace()方法被设计成在使用string查找匹配时仅替换第一次出现的情况。检查更换方法。

要替换所有匹配项,您可以使用以下3种方法:

use regex with the global flag in replace() method: When you use the replace method with regex with /g flag it replaces all the matching occurrences in a string. function updateKey() { var key=$("#title").val(); key=key.replace(/ /g,"_"); $("#url_key").val(key); } // Show case let title = "Your document title"; console.log(title.replace(/ /g,"_")); Using replaceAll method: The replaceAll method will remove all spaces with an underscore. (must use the global flag with it when using regex) function updateKey() { var key=$("#title").val(); key=key.replaceAll(/ /g,"_"); // key=key.replaceAll(" ","_"); also valid $("#url_key").val(key); } // Show case let title = "Your document title"; console.log(title.replaceAll(/ /g,"_")); Use a combination of split and join method: Split your string at spaces and join it by using _ as a separator in the join method. function updateKey() { var key=$("#title").val(); key=key.split(" ").join("_"); $("#url_key").val(key); } // Show case let title = "Your document title"; console.log(title.split(" ").join("_"));

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

下面来回答Prasanna的问题:

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

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

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

你可以试试这个

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

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