482

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Omar Abid
  • 15,753
  • 28
  • 77
  • 108
  • 9
    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 01:32
  • rubular.com is what you're looking for – LanguagesNamedAfterCofee Jul 17 '12 at 15:41
  • 1
    [Don't use a regex](http://jsperf.com/replace-vs-split-join-vs-replaceall/24) for something this trivial. – Steven Lu May 02 '13 at 18:42
  • Unfortunately it does not look like a non-regex can allow for replacement of a string multiple times. – Steven Lu May 04 '13 at 23:41
  • Possible duplicate of [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/q/1144783/1529630) – Oriol Oct 10 '15 at 23:34

17 Answers17

901

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

mystring = mystring.replace(/\./g,' ')
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
aefxx
  • 24,835
  • 6
  • 45
  • 55
319

One more solution which is easy to understand :)

var newstring = mystring.split('.').join(' ');
insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
Umesh Patil
  • 10,475
  • 16
  • 52
  • 80
  • 27
    @HaggleLad because you don't need to mess with regex – ton.yeung Apr 04 '12 at 03:30
  • 6
    Isn't this much slower than regexing? – Jasper Kennis Jun 06 '12 at 14:10
  • 1
    @Jasper from my understanding, it's actually faster in most browsers, although I haven't actually benchmarked it myself. – andrew Jun 26 '12 at 21:58
  • 10
    @BetoFrega Nothing like some empirical data to make your case :). Thanks for providing the link! – testing123 Sep 28 '12 at 04:41
  • 4
    If you use RegExp, you do want to store the regex in a separate variable outside the loop. Compiling/interpreting a regex takes some time, but once it's compiled, it can be used pretty fast. Please try these tests I made: http://jsperf.com/replace-vs-split-join-vs-replaceall/23 – sanderd17 Apr 15 '13 at 09:02
  • 1
    @sanderd17, in general you are absolutely right. Anyway, I think the original test is accurate, as it measures the individual overhead of creating a RegExp compared to parsing it from a js regex string, and using string split/join. In the general use cases, you cannot cache sting split logic, so relevance is preserved by not caching the regex string or RegExp object. – Ivaylo Slavov Aug 26 '13 at 09:28
  • 1
    Hm I prefer this solution over the slashy regex syntax because it's totally easy to read and understand, but I wonder how this solution actually was faster on Chrome 28.0.1455 (1) according to the test result posted above? – beta Sep 25 '13 at 10:29
54
/**
 * 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...

EDIT:
Maybe at the time I did this code I did not used jsperf. But in the end such discussion is totally pointless, the performance difference is not worth the legibility of the code in the real world, so my answer is still valid, even if the performance differs from the regex approach.

EDIT2:
I have created a lib that allows you to do this using a fluent interface:

replace('.').from('okay.this.is.a.string').with(' ');

See https://github.com/FagnerMartinsBrack/str-replace.

Fagner Brack
  • 2,365
  • 4
  • 33
  • 69
  • 1
    Very useful. FYI: There are rogue characters after the semi-colon in the alert statement. – Patrick Nov 27 '12 at 11:24
  • What you mean for "rogue character"? – Fagner Brack Feb 06 '13 at 23:09
  • 1
    He means entity & #8203 ; twice, which is Unicode Character 'ZERO WIDTH SPACE' (U+200B). More information on http://www.fileformat.info/info/unicode/char/200b/index.htm – Cœur Feb 07 '13 at 14:07
  • @FagnerBrack You should probably move the `str.toLowerCase()` out of the loop for performance reasons. Also, manipulating the string that you're searching on is probably less than optimal. I posted an answer with a modified version: http://stackoverflow.com/questions/2390789/how-to-replace-all-periods-in-a-string-in-javascript/16661977#16661977 – sstur May 21 '13 at 04:20
  • @sstur I suppose it is required to lowercase the string again after manipulation. Is manipulating the string I am searching a considerable difference in performance? I suppose the legibility goes over the benefits (untested). – Fagner Brack Jan 16 '14 at 20:41
22
str.replace(new RegExp(".","gm")," ")
macemers
  • 2,194
  • 6
  • 38
  • 55
16

For this simple scenario, i would also recommend to use the methods that comes build-in in javascript.

You could try this :

"okay.this.is.a.string".split(".").join("")

Greetings

Victor
  • 3,841
  • 2
  • 37
  • 63
6

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);
kittichart
  • 61
  • 1
  • 1
6

replaceAll(search, replaceWith) [MDN]

 ".a.b.c.".replaceAll('.', ' ')
 // result: " a b c "

 // Using RegEx. You MUST use a global RegEx.
 ".a.b.c.".replaceAll(/\./g, ' ')
 // result: " a b c "
    

replaceAll() replaces ALL occurrences of search with replaceWith.

It's actually the same as using replace() [MDN] with a global regex(*), merely replaceAll() is a bit more readable in my view.

(*) Meaning it'll match all occurrences.


Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

Raz
  • 434
  • 7
  • 6
  • I like this better than the top answer because it's basically the same but simpler since it shows you don't have to use regex for something this simple. (I'm not sure why most answers assume you need to use regex) – gamingexpert13 May 12 '21 at 17:01
  • It's important to take into account the compatibility with older browsers. I was using this in production and had to change it to `replace` with RegEx or `split('.').join('')` because of this. – Javi Marzán Jul 15 '21 at 12:43
4

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)'));
sstur
  • 1,769
  • 17
  • 22
  • 1
    Actually, it appears escaped RegEx performs better than indexOf! Doesn't sound right, but JSPerf indicates it's much faster: http://jsperf.com/replaceall-indexof-vs-regex – sstur May 21 '13 at 05:27
  • Maybe at the time I did that code I did not used jsperf. But in the end such discussion is totally pointless, the performance difference is not worth the legibility of the code in the real world, so my answer is still valid. – Fagner Brack Jan 16 '14 at 20:32
2
String.prototype.replaceAll = function(character,replaceChar){
    var word = this.valueOf();

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

    return word;
}
Joel
  • 111
  • 8
  • 4
    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 '13 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 03 '13 at 09:46
2

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");

scripto
  • 2,297
  • 1
  • 14
  • 13
  • 1
    This doesn't handle case-insensitive search/replace. So it is functionally equivalent to: `string.split(stringToFind).join(stringToReplace)` – sstur May 21 '13 at 04:09
0

Example: I want to replace all double Quote (") into single Quote (') Then the code will be like this

var str= "\"Hello\""
var regex = new RegExp('"', 'g');
str = str.replace(regex, '\'');
console.log(str); // 'Hello'
Brandon Anzaldi
  • 6,884
  • 3
  • 36
  • 55
Neel Kamal
  • 221
  • 3
  • 2
0

@scripto's made a bit more concise and without prototype:

function strReplaceAll(s, stringToFind, stringToReplace) {
    if (stringToFind === stringToReplace) return s;
    for (let index = s.indexOf(stringToFind); index != -1; index = s.indexOf(stringToFind))
        s = s.replace(stringToFind, stringToReplace);
    return s;
}

Here's how it stacks up: http://jsperf.com/replace-vs-split-join-vs-replaceall/68

A T
  • 13,008
  • 21
  • 97
  • 158
0
String.prototype.replaceAll = function (needle, replacement) {
    return this.replace(new RegExp(needle, 'g'), replacement);
};
Danon
  • 2,771
  • 27
  • 37
0
mystring.replace(new RegExp('.', "g"), ' ');
Idan
  • 3,604
  • 1
  • 28
  • 33
0

Simplest way

"Mr.".split('.').join("");

..............

Console

enter image description here

Vinod Kumar
  • 1,191
  • 14
  • 12
-1

you can replace all occurrence of any string/character using RegExp javasscript object.

Here is the code,

var mystring = 'okay.this.is.a.string';

var patt = new RegExp("\\.");

while(patt.test(mystring)){

  mystring  = mystring .replace(".","");

}
tomvodi
  • 5,577
  • 2
  • 27
  • 38
Rakesh Chaudhari
  • 3,310
  • 1
  • 27
  • 25
-6
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, "'");
} 
Neha
  • 170
  • 5