0

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:

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

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);
elixenide
  • 44,308
  • 16
  • 74
  • 100
Digital Brent
  • 1,275
  • 7
  • 19
  • 47
  • Or maybe [How to replace all dots in a string using JavaScript](http://stackoverflow.com/q/2390789/1529630) was a better duplicate? – Oriol May 10 '15 at 17:57

2 Answers2

3

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

var str_words = the_string.replace(/\./g, "");
elixenide
  • 44,308
  • 16
  • 74
  • 100
0

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));
user1823
  • 1,111
  • 6
  • 19