我想转义仅在文本之后出现的所有引号H1:
例如, :
H1: "text here"
应该变成:
H1: "text here"
使用lookbehind这很容易,但这不是在JS中。
我试过的东西:
.replace(/H1:(.*)(")(.*)/ig, "H1:$1"$2")
它也应该适用于其他类似的文本,如:
H1: ""text here""
H1: "text "here""
H1: ""text here"
我想转义仅在文本之后出现的所有引号H1:
例如, :
H1: "text here"
应该变成:
H1: "text here"
使用lookbehind这很容易,但这不是在JS中。
我试过的东西:
.replace(/H1:(.*)(")(.*)/ig, "H1:$1"$2")
它也应该适用于其他类似的文本,如:
H1: ""text here""
H1: "text "here""
H1: ""text here"
这是一种方法:
function encodeQuotesOccuringAfter(string, substring) {
if(string.indexOf(substring) == -1) {
return string;
}
var all = string.split(substring);
var encoded = [all.shift(), all.join(substring).replace(/"/g, """)];
return encoded.join(substring)
}
第二个有点浪费,但你可以把它移到一个函数中,startAt
只计算一次。想法是查找所有引号,只更改前面出现“H1:”的引号。
str.replace(/"/g, function(match, offset, string) {
var startAt = string.indexOf("H1:");
if(startAt != -1 && offset > startAt) {
return """;
}
else {
return '"';
}
});
使用我们H1:
不包含引号的领域知识,我们只需对整个字符串进行替换。
str.replace(/"/g, """);
将文本分成几行,然后,对于以“H1”开头的每一行,只需进行替换即可。
请注意,“ 如果它嵌入在 HTML 中,则 JavaScript 引擎可以用真正的引号替换字符。(编辑:当我尝试直接在这个答案中写它时它被替换了)。
试试这个:
.replace(/H1:(.*?)(")(.*?)/ig, "H1:$1"$3")
*? 匹配 0 个或多个前面的标记。这是一个惰性匹配,在满足下一个标记之前将匹配尽可能少的字符。
这是我用来测试正则表达式的网站:http: //gskinner.com/RegExr/
首先,我将字符串分成几行。然后我只在正确的行上进行文本替换,当我进行文本替换时,我将所有行重新连接在一起:
<script type="text/javascript">
// Create a test string.
var string='H1: "text here" \nH1: test "here" \nH2: not "this" one';
// Split the string into lines
array = string.split('\n');
// Iterate through each line, doing the replacements and
// concatenating everything back together
var newString = "";
for(var i = 0; i < array.length; i++) {
// only do replacement if line starts H1
// /m activates multiline mode so that ^ and $ are start & end of each line
if (array[i].match(/^H1:/m) ) {
// Change the line and concatenate
// I used "e; instead of "e; so that the changes are
// visible with document.write
newString += array[i].replace(/"/g, '"e;') + '\n';
} else {
// only concatenate
newString += array[i] + '\n';
}
}
document.write(newString);
</script>