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

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();
});

其他回答

试试这个:

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

它会做全局查找/替换

javascript替换

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

$(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();
});

const updateKey = key => console.log(key。分割(' '). join(“_”)); updateKey(“Hello World”);

替换所有事件

之所以会出现这种情况,是因为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("_"));