字符串替换不替换字符的第二个实例[重复]

时间:2021-05-17 19:34:29

This question already has an answer here:

这个问题在这里已有答案:

I have a simple code right here that is supposed to take the periods out of a string and then split all the words into an array. The array part works fine, but using .replace on my string only removes the first period. Isn't it supposed to remove all instances of a period? The result I get in the console is:

我在这里有一个简单的代码,它应该从字符串中取出句点,然后将所有单词拆分成一个数组。数组部分工作正常,但在我的字符串上使用.replace只删除第一个句点。是不是应该删除一段时间的所有实例?我在控制台中得到的结果是:

["This", "is", "a", "test", "of", "the", "emergency", "broadcast", "system", "This", "is", "only", "a", "test."]

[“This”,“is”,“a”,“test”,“of”,“the”,“emergency”,“broadcast”,“system”,“This”,“is”,“only”,“一个测试。”]

As you can see the last period is still there. Why is it not being removed by my string replace and how can I take all the periods out of the string?

正如你所看到的那样,最后一段时期仍然存在。为什么我的字符串替换不会删除它,如何从字符串中取出所有句点?

Here is my code:

这是我的代码:

var the_string = "This is a test of the emergency broadcast system. This is only a test.";
var str_words = the_string.replace(".", "");
str_words = str_words.split(" ");
console.log(str_words);

2 个解决方案

#1


You need to use a regex with the g (global) flag.

您需要使用带有g(全局)标志的正则表达式。

var str_words = the_string.replace(/\./g, "");

#2


You can do the following by splitting the string then using a map to remove the period(s):

您可以通过拆分字符串然后使用地图删除句点来执行以下操作:

var the_string = "This is a test of the emergency broadcast system. This is only a test.";
var str_word = the_string.split(" ").map(function(x){return x.replace(".", "")})
alert(JSON.stringify(str_word));

#1


You need to use a regex with the g (global) flag.

您需要使用带有g(全局)标志的正则表达式。

var str_words = the_string.replace(/\./g, "");

#2


You can do the following by splitting the string then using a map to remove the period(s):

您可以通过拆分字符串然后使用地图删除句点来执行以下操作:

var the_string = "This is a test of the emergency broadcast system. This is only a test.";
var str_word = the_string.split(" ").map(function(x){return x.replace(".", "")})
alert(JSON.stringify(str_word));