Developer Desk
Developer Desk

Reputation: 2344

replace all special character in string javascript....?

Why this does not replace ?

code:

   var str = "fq$team$456$$$$fq$plrs$4789";
    if(str.indexOf("$$$$")>=0){
        str = str.replace("$$$$","$$");
    }

   // gives fq$team$456$fq$plrs$4789


   // expected output = fq$team$456$$fq$plrs$4789 

Upvotes: 2

Views: 70

Answers (3)

DanielST
DanielST

Reputation: 14133

$$ means $ in the replace parameter. MDN:

$$ Inserts a "$".

Use

var str = "fq$team$456$$$$fq$plrs$4789";
if(str.indexOf("$$$$")>=0){
    str = str.replace("$$$$","$$$$");
}
console.log(str); //fq$team$456$$fq$plrs$4789

Upvotes: 2

Valijon
Valijon

Reputation: 13103

Try split/join

var str = "fq$team$456$$$$fq$plrs$4789";
    if(str.indexOf("$$$$")>=0){
        str = str.split("$$$$").join("$$");
    }

console.log(str)

Upvotes: 2

Andrew Larson
Andrew Larson

Reputation: 483

According to the MDN docs, $$ is supposed to insert a single $. This is the result of the $ character being used to form some special string patterns.

Upvotes: 4

Related Questions