André Silva
André Silva

Reputation: 1108

Javascript replace special characters

Let's say I want to replace this:

Test%20Test

into this:

Test\X20\Test

I know this sounds weird but I need for the string to look like that. And I can't get my head around this because of the last backlash. Is there any way with .replace() to achieve that? If I wanted just Test\X20Test I could easily do string.replace(/%/g, '\\X'); but I need the backlash after the hexadecimal code.

Upvotes: 0

Views: 81

Answers (1)

epascarello
epascarello

Reputation: 207557

simple capture group would work.

"Test%20Test".replace(/%([0-9A-F]{2})/ig, "\\X$1\\");

Upvotes: 1

Related Questions