js 正则表达式转义引号
我想转义仅在文本 H1:
之后出现的所有引号,
例如, :
H1: "text here"
应该变成:
H1: "text here"
这对于后向查找来说很容易,但这不是 JS 中的。
我尝试过的东西:
.replace(/H1:(.*)(")(.*)/ig, "H1:$1"$2")
它也应该适用于其他类似的文本,例如:
H1: ""text here""
H1: "text "here""
H1: ""text here"
I want to escape all quotes that comes only after the text H1:
For instance, :
H1: "text here"
should become:
H1: "text here"
This would be easy with lookbehind, but that's not in JS.
something I tried:
.replace(/H1:(.*)(")(.*)/ig, "H1:$1"$2")
Also it should work on other similar text like:
H1: ""text here""
H1: "text "here""
H1: ""text here"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将文本分成几行,然后,对于以“H1”开头的每一行,只需进行替换即可。
请注意,"如果字符嵌入在 HTML 中,JavaScript 引擎可能会将其替换为真正的引号。 (编辑:当我尝试直接写在这个答案中时,它被替换了)。
Split the text into lines, then, for every line that begins with "H1", simply do a replace.
Just be aware that the " character may be replaced by the JavaScript engine with a real quote if it's embedded inside HTML. (Edit: it got replaced when I tried to write it directly in this answer).
这是一种方法:
第二种方法有点浪费,但您可以将其移至函数中,并且仅计算
startAt
一次。想法是查找所有引号,只更改前面出现“H1:”的引号。利用我们的领域知识,
H1:
不包含引号,我们只需对整个字符串进行替换即可。Here's one approach:
This second one is a bit wasteful, but you could move this into a function, and compute
startAt
only once. Idea is to look for all quotes, and only change the ones that have "H1:" appear before them.Using our domain knowledge that
H1:
does not contain quotes, we simply do a replace on the entire string.首先,我将字符串分成几行。
然后我只在正确的行上进行文本替换,当我进行文本替换时,我将所有行重新连接在一起:
First I split the string into lines.
Then I only do the text replacement on the correct lines, and while I do the text replacement I concatenate all the lines back together:
试试这个:
*?匹配 0 个或多个前面的标记。这是一个惰性匹配,在满足下一个标记之前将匹配尽可能少的字符。
这是我用来测试正则表达式的网站:
http://gskinner.com/RegExr/
try this:
*? Matches 0 or more of the preceeding token. This is a lazy match, and will match as few characters as possible before satisfying the next token.
This is the web site that I use for testing regular expressions:
http://gskinner.com/RegExr/