我这里有一个简单的代码,应该从字符串中取出句点,然后将所有单词拆分到一个数组中。数组部分工作正常,但使用 .replace
在我的字符串上仅删除第一个句点。它不是应该删除一个句点的所有实例吗?我在控制台中得到的结果是:
["This", "is", "a", "test", "of", "the", "emergency", "broadcast", "system", "This", "is", "only", "a", "test."]
如您所见,最后一个周期仍然存在。为什么我的字符串替换没有删除它以及如何从字符串中取出所有句点?
这是我的代码:
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);
最佳答案
您需要使用带有 g
(全局)标志的正则表达式。
var str_words = the_string.replace(/\./g, "");
关于javascript - 字符串替换不会替换字符的第二个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30154676/