对于这种特定情况,如何使用 JavaScript 替换字符串中的所有字符:replace 。经过 _

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3103056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:16:34  来源:igfitidea点击:

How to replace all characters in a string using JavaScript for this specific case: replace . by _

javascriptregex

提问by Kevin Le - Khnle

The following statement in JavaScript works as expected:

JavaScript 中的以下语句按预期工作:

var s1 = s2.replace(/ /gi, '_'); //replace all spaces by the character _

However, to replace all occurrences of the character . by the character _, I have:

但是,要替换所有出现的字符 . 通过字符_,我有:

var s1 = s2.replace(/./gi, '_');

But the result is a string entirely filled with the character _

但结果是一个完全用字符 _ 填充的字符串

Why and how to replace . by _ using JavaScript?

为什么以及如何更换 . 通过 _ 使用 JavaScript?

回答by Jacob Mattison

The . character in a regex will match everything. You need to escape it, since you want a literal period character:

这 。正则表达式中的字符将匹配所有内容。你需要转义它,因为你想要一个文字句点字符:

var s1 = s2.replace(/\./gi, '_');

回答by SilentGhost

you need to escape the dot, since it's a special character in regex

您需要转义点,因为它是正则表达式中的特殊字符

s2.replace(/\./g, '_');

Note that dot doesn't require escaping in character classes, therefore if you wanted to replace dots and spaces with underscores in one go, you could do:

请注意,点不需要在字符类中转义,因此如果您想一次性用下划线替换点和空格,您可以这样做:

s2.replace(/[. ]/g, '_');

Using iflag is irrelevant here, as well as in your first regex.

i在这里以及在您的第一个正则表达式中使用标志都无关紧要。

回答by dbrown0708

You can also use strings instead of regular expressions.

您还可以使用字符串代替正则表达式。

var s1 = s2.replace ('.', '_', 'gi')

回答by HoLyVieR

There is also this that works well too :

还有这个也很好用:

var s1 = s2.split(".").join("_"); // Replace . by _ //