在JavaScript中用下划线替换空格?

462

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

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

894

尝试使用.replace(/ /g,"_");

编辑: 如果您不喜欢正则表达式,也可以使用.split(' ').join('_')

编辑: John Resig说过:

如果您正在对具有静态搜索和静态替换的字符串执行搜索和替换,则使用 .split("match").join("replace") 执行操作速度更快 - 这似乎违反直觉,但在大多数现代浏览器中它能够这样工作。 (下一版本的Firefox中存在改进.replace(/match/g, "replace")性能的变化 - 因此以前的说法不会再长时间存在。)


2
有没有不用正则表达式的方法来实现这个? - Ali
1
为什么回答的人没有使用 /\s/g? - epascarello
8
在Javascript中,可以使用/\ /g来代替/ /g。两者都是可行的方法。而在CoffeeScript中只有后者有效。 - Tom Leys
42
截至2015年,.replace(/ /g,"_");.split(' ').join('_') 更快。 - Gabriel Tomitsuka
11
未来浏览此页面的人,@Inez 提供了一个测试分割/合并和替换速度的链接。截至2018年末,替换明显更快。 - ricks
显示剩余6条评论

97

试一下这个:

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

这将进行全局查找和替换

javascript replace


漂亮的代码!!!它成功了!!! - Hugo Barbosa

72

回答Prasanna在下面提出的问题:

如何在JavaScript中将多个空格替换为单个空格?

您将使用相同的replace函数,但使用不同的正则表达式。空白的表达式是\s,而“1次或更多次”的表达式是+加号,因此您只需用以下内容替换Adam的回答:

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

55

你可以试试这个

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

它甚至将多个空格替换为单个“-”。


5
值得注意的是:这也会去掉制表符和其他空白字符。 - Berry M.

20

用下划线替换空格

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

输出:你好吗


19

1
现在看来,“替换”似乎是更好的选择。 - Houman
Kave - 什么?虽然不是所有的浏览器都相同,但平均分割/连接要好得多。事实上,在许多现代浏览器中,它要好得多!感谢Inez设置这个! - David Hobs
4
现在已经过去一年多了,在Chrome 32.0.1700.107中运行上述测试,str.replace()的表现要好得多(快了64%)。 - jenovachild

8

替换所有出现

之所以会发生这种情况,是因为replace()方法是这样设计的,当您使用字符串查找匹配时,它只替换第一个匹配项。请检查replace方法。

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

  1. 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,"_"));

  2. 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,"_"));

  3. 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("_"));


4

Just using replace:

var text = 'Hello World';
    
new_text = text.replaceAll(' ', '_');
    
console.log(new_text);


15
这将仅替换第一个非后续空格。 - Narendra
这个答案应该被删除,因为楼主尝试过了但失败了。 - Peter Moore
使用replaceAll方法可以实现此功能。(该方法不支持IE浏览器。) - Paul Moers

3

我知道这已经过时了,但是我没有看到有人提到扩展字符串prototype

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

4
这是一个可怕的想法,因此你没有看到任何人这样做。 查看这个其他的SO问题获取更多信息。 - user9016207

1

const updateKey = key => console.log(key.split(' ').join('_'));
updateKey('Hello World');


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接