Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to replace all the occurances of a period (.) 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.

Any idea how to resolve this?

share|improve this question
5  
aefxx's answer is correct, but just as an FYI is that the period character in a regex means match everything, thus everything being a space. Escaping it with the backslash means match on periods. – swilliams Jul 27 '10 at 16:52
Thanks for the tip. I have has some AHA moments (when building the app) with Regex. I really hate it _, do you have some cool, good tutorial? – Omar Abid Jul 31 '10 at 1:32
rubular.com is what you're looking for – LanguagesNamedAfterCofee Jul 17 '12 at 15:41
Don't use a regex for something this trivial. – Steven Lu May 2 at 18:42
Unfortunately it does not look like a non-regex can allow for replacement of a string multiple times. – Steven Lu May 4 at 23:41

9 Answers

up vote 262 down vote accepted

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

mystring.replace(/\./g,' ')
share|improve this answer
8  
just to clarify, the \ escapes special characters in regular expressions, like the . in this case – realgt Sep 27 '11 at 20:30
looks like sed.. somehow.. :) – Paschalis Jul 9 '12 at 19:23

One more solution which is easy to understand :)

var newstring = mystring.split('.').join(' ');
share|improve this answer
6  
I like this for some reason. – HaggleLad Mar 23 '12 at 9:09
12  
@HaggleLad because you don't need to mess with regex – ton.yeung Apr 4 '12 at 3:30
4  
Isn't this much slower than regexing? – Jasper Kennis Jun 6 '12 at 14:10
52  
5  
@BetoFrega Nothing like some empirical data to make your case :). Thanks for providing the link! – testing123 Sep 28 '12 at 4:41
show 5 more comments
/**
 * ReplaceAll by Fagner Brack (MIT Licensed)
 * Replaces all occurrences of a substring in a string
 */
String.prototype.replaceAll = function( token, newToken, ignoreCase ) {
    var _token;
    var str = this + "";
    var i = -1;

    if ( typeof token === "string" ) {

        if ( ignoreCase ) {

            _token = token.toLowerCase();

            while( (
                i = str.toLowerCase().indexOf(
                    token, i >= 0 ? i + newToken.length : 0
                ) ) !== -1
            ) {
                str = str.substring( 0, i ) +
                    newToken +
                    str.substring( i + token.length );
            }

        } else {
            return this.split( token ).join( newToken );
        }

    }
return str;
};

alert('okay.this.is.a.string'.replaceAll('.', ' '));

Faster than using regex...

share|improve this answer
1  
thanks a lot :) – peplamb May 2 '12 at 23:41
1  
Very useful. FYI: There are rogue characters after the semi-colon in the alert statement. – Patch Nov 27 '12 at 11:24
What you mean for "rogue character"? – Fagner Brack Feb 6 at 23:09
1  
He means entity & #8203 ; twice, which is Unicode Character 'ZERO WIDTH SPACE' (U+200B). More information on fileformat.info/info/unicode/char/200b/index.htm – Cœur Feb 7 at 14:07
Oh got it, thanks! – Fagner Brack Feb 7 at 20:33
show 1 more comment
str.replace(new RegExp(".","gm")," ")
share|improve this answer
1  
Worked great for replace function =) – afreeland Jul 26 '12 at 18:09

I add double backslash to the dot to make it work. Cheer.

var st = "okay.this.is.a.string";
var Re = new RegExp("\\.","g");
st = st.replace(Re," ");
alert(st);
share|improve this answer
String.prototype.replaceAll = function(character,replaceChar){
    var word = this.valueOf();

    while(word.indexOf(character) != -1)
        word = word.replace(character,replaceChar);

    return word;
}
share|improve this answer
won't this get stuck in an infinite loop if you give it something like: replaceAll('&', '&') ? (admittedly that is not a case in the OP's question) – Anentropic Jun 17 at 14:19
But "&" contains a & so the loop never runs out of things to replace (and the string keeps on growing). I tried it just now and it locked up my browser... – Anentropic Jul 3 at 9:46

Here's another implementation of replaceAll. Hope it helps someone.

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if (stringToFind === stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

Then you can use it:

var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");

share|improve this answer
1  
This doesn't handle case-insensitive search/replace. So it is functionally equivalent to: string.split(stringToFind).join(stringToReplace) – sstur May 21 at 4:09

This is more concise/readable and should perform better than the one posted by Fagner Brack (toLowerCase not performed in loop):

String.prototype.replaceAll = function(search, replace, ignoreCase) {
  if (ignoreCase) {
    var result = [];
    var _string = this.toLowerCase();
    var _search = search.toLowerCase();
    var start = 0, match, length = _search.length;
    while ((match = _string.indexOf(_search, start)) >= 0) {
      result.push(this.slice(start, match));
      start = match + length;
    }
    result.push(this.slice(start));
  } else {
    result = this.split(search);
  }
  return result.join(replace);
}

Usage:

alert('Bananas And Bran'.replaceAll('An', '(an)'));
share|improve this answer
1  
Actually, it appears escaped RegEx performs better than indexOf! Doesn't sound right, but JSPerf indicates it's much faster: jsperf.com/replaceall-indexof-vs-regex – sstur May 21 at 5:27
var mystring = 'okay.this.is.a.string';
var myNewString = escapeHtml(mystring);

function escapeHtml(text) {
if('' !== text) {
    return text.replace(/&/g, "&")
               .replace(/&lt;/g, "<")
               .replace(/&gt;/g, ">")
               .replace(/\./g,' ')
               .replace(/&quot;/g, '"')
               .replace(/&#39/g, "'");
} 
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.