3

i'm trying to replace '$$$' with space using JavaScript. simple as that.

I have the following code:

var splitSign = '$$$';
var string = 'hello$$$how$$$are$$$you';
var regex = new RegExp(splitSign,'g');
var res = string.replace(regex,' ');
console.info(res);

the result is the string not modified! any ideas why ?

ufk
  • 30,912
  • 70
  • 235
  • 386

5 Answers5

5

You don't need regex for this, you can use split and join. This will be faster than regex.

string.split(splitSign).join(' ');

split will split the text by $$$ and return array. join will join the elements of the array by space and return string.

Tushar
  • 85,780
  • 21
  • 159
  • 179
1

$ has a special meaning in the context of a regex, it marks the end of a line/string.

You have to escape it:

var splitSign = '\\$\\$\\$';
Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
0

You have to escape $.. since it is a special character in regex (meaning end of the string)

var splitSign = '\\$\\$\\$';    (if creating new RegExp)

Otherwise just use:

string.replace(/\$\$\$/g,' ');

Code:

var splitSign = '\\$\\$\\$';
var string = 'hello$$$how$$$are$$$you';
var regex = new RegExp(splitSign,'g');
var res = string.replace(regex,' ');
alert(res);
karthik manchala
  • 13,492
  • 1
  • 31
  • 55
0

$ is a special meta character in regular expressions. It indicates the end of the string in the same way that ^ indicates the beginning.

In order to use these special characters, you have to escape them by preceding them with a backslash - this will result in the regex engine using the character literally and not parsing it as a special meta character. However because you are using the RegExp constructor you'll need to double escape the special meta characters.

var splitSign = '\\$\\$\\$';

As was mentioned in other answers, what you are trying to do is easily accomplished without regular expressions. A simple string.replace would suffice here. If you want to replace multiple instances, you can provide the g flag to specify a global match.

Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Community
  • 1
  • 1
Lix
  • 47,311
  • 12
  • 103
  • 131
0

as i explained... string.replace without RegExp only changes the first occurrence in a string.

i found the following answer: How to replace all occurrences of a string in JavaScript?

it has exactly what I need.

first.. auto escaping a string:

function escapeRegExp(string) { 
  return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

and then the replace function

function replaceAll(string, find, replace) {
 return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);  
}
Community
  • 1
  • 1
ufk
  • 30,912
  • 70
  • 235
  • 386