with a space using JavaScript. just like this. I have the following code: var spli...">

How to use RegExp correctly

I am trying to replace '$$$' with a space using JavaScript. just like this.

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

      

As a result, the string does not change! any ideas why?

+3


source to share


5 answers


You don't need to do this regex

, you can use split

and join

. It will be faster than regex

.

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

      



split

will split the text by $$$

and return an array. join

joins the array elements by space and returns a string.

+5


source


$

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

You need to avoid this:



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

      

+1


source


You need to exit $

.. as this is a special character in regex (meaning of end of line)

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

Run codeHide result


0


source


$

- a special metacharacter in regular expressions. It indicates the end of the line, just as it ^

indicates the beginning.

To use these special characters, you must avoid them by preceding them with a backslash - this will cause the regex engine to literally use the character and not parse it as a special metacharacter. However, due to the fact that you are using the constructor RegExp

, you need to double the allocation of special metacharacters.

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

      

As mentioned in other answers, what you are trying to do is easily accomplished without regex. Simple enough here string.replace

. If you want to replace multiple instances, you can specify a flag g

to indicate global match.

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

0


source


as i explained ... string.replace without RegExp only changes the first occurrence of the 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 string:

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

      

and then replace the function

function replaceAll(string, find, replace) {
 return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);  
}

      

0


source







All Articles