Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all dots in a string using JavaScript

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.

like image 411
Omar Abid Avatar asked Mar 06 '10 00:03

Omar Abid


People also ask

How do you replace all occurrences of a character in a string in JavaScript?

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.

Is there a Replace All in JavaScript?

replaceAll() (at stage 4) that brings the replace all method to JavaScript strings. This is the most convenient approach.

What is replace (/ g in JavaScript?

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.


2 Answers

You need to escape the . because it has the meaning of "an arbitrary character" in a regular expression.

mystring = mystring.replace(/\./g,' ') 
like image 160
aefxx Avatar answered Sep 23 '22 00:09

aefxx


One more solution which is easy to understand :)

var newstring = mystring.split('.').join(' '); 
like image 45
Umesh Patil Avatar answered Sep 23 '22 00:09

Umesh Patil