Javascript正则表达式查找某些字符之间的双引号

时间:2013-07-17 18:47:01

标签: javascript regex

我正在尝试创建一个可以解析为JSON的字符串。该字符串是根据CMS中的内容动态创建的。 该内容可能包含带双引号的HTML标记,这会混淆JSON解析器。因此,我需要用"替换HTML中的双引号而不替换实际上是JSON结构一部分的双引号。 我的想法是将HTML包含在标记中,我可以使用它来识别这些标记之间的所有内容作为我想要替换的引号。 例如,我想要解析为JSON的字符串可能看起来像这样......

str = '{"key1":"XXX<div id="divId"></div>YYY", "key2":"XXX<div id="divId"></div>YYY"}';

所以,我想用&quot;替换XXX和YYY之间的每个双引号。 有点像...

str = str.replace(/XXX(")YYY/g, '&quot;');

希望有道理。感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

鉴于Stack Overflow的“我们不做你的功课”原则,我认为我不会完成整个解决方案,但我可以给你一些半完成代码的指示。

var xySearch = /this regex should find any text between XXX...YYY/g;
// note the g at the end! That's important
var result;
var doubleQuoteIndices = [];
// note the single-equals. I avoid them when possible inside a "condition" statement,
// but here it sort of makes sense.
while (result = xySearch.exec(str)) {
  var block = result[0];
  // inside of the block, find the index in str of each double-quote, and add it
  // to doubleQuoteIndices. You will likely need result.lastIndex for the absolute position.

}

// loop backwards through str (so that left-side replacements don't change right-side indexes)
// to replace the characters at each doubleQuoteIndices with the appropriate HTML.

我发现像正则表达式一样对于某些模式,使用编程语言做一些工作通常是最好的解决方案。

相关问题