sidney
sidney

Reputation: 2714

Prepend backslashes for every dot

I'd like to prepend backslasher for every dot which is present in javascript. For instance:

this.is.a.test 

will give

this\\.is\\.a\\.test

I tried this :

a = "this.is.a.test";
b = a.replace(".","\\.");

but b returns this\.is.a.test instead of this\\.is\\.a\\.test

Backslashes are used to escape strings, so how can I fix it?

Upvotes: 0

Views: 54

Answers (1)

Anton
Anton

Reputation: 32581

Try this

a = "this.is.a.test";
b = a.replace(/\./g,"\\.");
//returns "this\.is\.a\.test"

for two backslashes do this

a = "this.is.a.test";
b = a.replace(/\./g,"\\\\.");
//returns "this\\.is\\.a\\.test"

Upvotes: 2

Related Questions