我这里有一个简单的代码,它应该从字符串中取出句点然后将所有单词拆分成一个数组。数组部分工作正常,但在我的字符串上使用.replace
只删除第一个句点。它不应该删除一段时期的所有实例吗?我在控制台中得到的结果是:
["这",""," a","测试","",& #34;","紧急","广播","系统","这","是&# 34;,"仅"," a","测试。"]
正如你所看到的那样,最后一段时期仍然存在。为什么我的字符串替换不会删除它,如何从字符串中取出所有句点?
这是我的代码:
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);
答案 0 :(得分:3)
您需要使用带有g
(全局)标记的正则表达式。
var str_words = the_string.replace(/\./g, "");
答案 1 :(得分:0)
您可以通过拆分字符串然后使用map
删除句点来执行以下操作:
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));