简体   繁体   English

JavaScript替换特殊字符

[英]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? .replace()有什么办法实现这一目标? If I wanted just Test\\X20Test I could easily do string.replace(/%/g, '\\\\X'); 如果我只想要Test\\X20Test我可以轻松地执行string.replace(/%/g, '\\\\X'); but I need the backlash after the hexadecimal code. 但我需要在十六进制代码后加反冲。

简单的捕获组将起作用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM