如何使用JavaScript替换字符串中的所有字符,以适应这种特殊情况:替换。由_

时间:2021-04-13 16:52:12

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 ?

4 个解决方案

#1


25  

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

的。regex中的字符将匹配所有内容。你需要转义它,因为你想要一个文字时期字符:

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

#2


6  

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

您需要转义这个点,因为它是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 i flag is irrelevant here, as well as in your first regex.

使用i标志在这里是不相关的,在您的第一个regex中也是如此。

#3


4  

You can also use strings instead of regular expressions.

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

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

#4


1  

There is also this that works well too :

还有一种方法也很有效:

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

#1


25  

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

的。regex中的字符将匹配所有内容。你需要转义它,因为你想要一个文字时期字符:

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

#2


6  

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

您需要转义这个点,因为它是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 i flag is irrelevant here, as well as in your first regex.

使用i标志在这里是不相关的,在您的第一个regex中也是如此。

#3


4  

You can also use strings instead of regular expressions.

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

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

#4


1  

There is also this that works well too :

还有一种方法也很有效:

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