I want to replace all the occurrences of a dot(.
) in a JavaScript string
For example, I have:
var mystring = 'okay.this.is.a.string';
I want to get: okay this is a string
.
So far I tried:
mystring.replace(/./g,' ')
but this ends up with all the string replaced to spaces.
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.
replaceAll() (at stage 4) that brings the replace all method to JavaScript strings. This is the most convenient approach.
The "g" that you are talking about at the end of your regular expression is called a "modifier". The "g" represents the "global modifier". This means that your replace will replace all copies of the matched string with the replacement string you provide.
You need to escape the .
because it has the meaning of "an arbitrary character" in a regular expression.
mystring = mystring.replace(/\./g,' ')
One more solution which is easy to understand :)
var newstring = mystring.split('.').join(' ');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With