简体   繁体   English

JavaScript中的正则表达式替换,用于转义用单引号引起来的特殊字符

[英]Regex replace in JavaScript for escaping special characters enclosed in single quotes

In my JavaScript file, I have a variable which takes values like the following 在我的JavaScript文件中,我有一个变量,其值类似于以下内容

stringToBeReplaced = input[name='Wanna Be Startin' Somethin'']

stringToBeReplaced = input[name='They Don't Care About Us']

stringToBeReplaced = input[name='Workin' Day & Night']

The pattern will be always like input[name='*'] with * could be anything. 该模式将始终像带有*的input[name='*'] What I am trying to achieve is to escape only the single quotes and ampersand (' &) appearing in the * field without escaping the enclosing single quotes using regex replace. 我想要实现的是仅转义*字段中出现的单引号和&符号('&),而不使用正则表达式替换转义包含单引号的内容。

The regex I have formed so far is as follows and what is still pending is to ignore the first single quote from the above pattern. 到目前为止,我已经形成的正则表达式如下,并且仍在等待中的是忽略上述模式中的第一个单引号。 ie the the single quote preceded by = sign 即单引号前面有=号

stringToBeReplaced.replace(/((['&])(?!\]))/g,'\\$1'));

Any help is much appreciated. 任何帮助深表感谢。

You can try like this: 您可以这样尝试:

(?<!=)(['&])(?!])

(?<!=) Negative look behind for = (?<!=)否定=

(['&]) Select the desired characters in character class and capture in group (['&])在字符类中选择所需的字符并在组中捕获

(?!]) Negative look ahead for closing ] (?!])负向展望]

Replace with: 用。。。来代替:

\\ and captured group \\和捕获的组

Demo: 演示:

https://regex101.com/r/CQbwtF/5 https://regex101.com/r/CQbwtF/5

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

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