-1

I am trying to make a regex search in JavaScript, but it doesn't work with special characters such as $ and +.

var string = "Keto After 50 $20 CPA+FS";
string.search(/Keto After 50 $20 CPA F+S/g);

I expect a match and a result of 0 instead of -1.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
medbelma
  • 1
  • 2

3 Answers3

0

Welcome!

We might just want to escape metachars:

(Keto After 50 \$20 CPA\+FS)

Test

const regex = /(Keto After 50 \$20 CPA\+FS)/gm;
const str = `Keto After 50 \$20 CPA+FS`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Please see this demo for additional info.

Emma
  • 27,428
  • 11
  • 44
  • 69
0

You can escape these special characters using a backslash (\):

var string = "Keto After 50 $20 CPA+FS";
console.log(string.search(/Keto After 50 \$20 CPA\+FS/g));

Also, you had a typo in your regex. I guess you meant to match "...CPA+FS", not "...CPA F+S".

Anis R.
  • 6,656
  • 2
  • 15
  • 37
0

Special characters should be preceded by a backslash. In a JavaScript regex, the following characters are special:

[ \ ^ $ . | ? * + ( )

So your code should be as follows:

var string = "Keto After 50 $20 CPA+FS";
string.search(/Keto After 50 \$20 CPA\+FS/g);
www.admiraalit.nl
  • 5,768
  • 1
  • 17
  • 32