字符串替换不替换字符的第二个实例
String replace does not replace second instance of character
我这里有一个简单的代码,它应该从字符串中取出句点,然后将所有单词拆分成一个数组。数组部分工作正常,但在我的字符串上使用 .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, "");
您可以通过拆分字符串然后使用 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));
我这里有一个简单的代码,它应该从字符串中取出句点,然后将所有单词拆分成一个数组。数组部分工作正常,但在我的字符串上使用 .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, "");
您可以通过拆分字符串然后使用 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));