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

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

当前回答

$(function() {
    $('#title').keyup(function() {
        var value = $(this).val().toLowerCase();
        $('#url_key').val(value.split(' ').join('_'));
    }).keyup();
});

——或者你可以用:

$(function() {
    $('#title').keyup(function() {
        var value = $(this).val().toLowerCase();
        $('#url_key').val(value.replace(/ /g,"_"));
    }).keyup();
});

其他回答

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

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

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 = 'How are you';
var replaced = str.split(' ').join('_');

输出:How_are_you

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

你可以试试这个

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

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