3

I want to replace all occurrences of .. with . . in a string. Basically, I don't want any . character being succeeded by another . character.

I've created this prototype function:

String.prototype.replaceAll = function (search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

However, whatever input I try, it results in the complete string being replaced with . characters, even though I've escaped the input and output string. What am I missing?

var description = 'hi there...how are you';
description = description.replaceAll('..', '. .');
description = description.replaceAll('\.\.', '\. \.');
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Adam
  • 6,041
  • 36
  • 120
  • 208

2 Answers2

3

\ is the escape character in string literals as well as regular expressions.

"\.\." produces the string value .., which, interpreted as regular expression, matches any two characters.

console.log('\.\.');

You need to escape the \ in the string literal to pass it along to the regular expression engine:

'\\.\\.'

produces the string value \.\..

String.prototype.replaceAll = function(search, replacement) {
  var target = this;
  return target.replace(new RegExp(search, 'g'), replacement);
};

var description = 'hi there...how are you';
console.log(description.replaceAll('\\.\\.', '. .'));

Having said that, using regular expression literal seems easier to me than hiding the g flag behind a custom method:

description.replace(/\.\./g, '. .');

No need to wonder about escape sequences.


Related: Is there a RegExp.escape function in Javascript?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

try

description.replace(/(\.)(?=\.)/g,'. ');

where

var description = 'hi there...how are you';
description = description.replace(/(\.)(?=\.)/g,'. ');

console.log(description);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345