首先我想说我对 javascript 非常陌生,基本上做了很多谷歌搜索来找到这个地方和各种其他资源。虽然我找到了一个脚本可以修改为我想要的内容(并设法使其工作),但它会干扰在指定 div 中创建的任何链接。有没有办法从 javascript 中排除链接,而只让 javascript 影响文本?
这是 JavaScript。虽然我可以毫无问题地让第一部分工作(其中我替换了引用的文本),但我似乎无法排除其中包含带有引号的 html 的链接和图像。
$("div.gam-posttem div").each(function(){
this.innerHTML = this.innerHTML.replace(/\"([^\"]+)\"/g,
'<div class="gam-quotetext">"$1"</div>');
});
$not('div.gam-posttem > div > a').each(function(){});
这是我正在使用的 html。
<div class="gam-posttem"><div class="gam-posttem1">
"quote here" and regular text here. "more quote here"
<br><br><a href="http://www.google.com">Link is Here</a>
</div></div>
非常感谢任何帮助,如果您需要更多信息,例如 CSS,请随时询问。
最佳答案
让这个问题特别棘手的是 JavaScript 正则表达式不允许向后查找。您想要做的是尝试匹配 "对,其中前面有相同数量的 < 和 > 字符(在其他 "字符之外)。即使你可以,那也会是一个看起来非常难看的正则表达式......
但是,您只关心 <> 对之外的字符,可以使用正则表达式进行匹配(虽然不建议):
<(?:[^><\"\']*?(?:([\"\']).*?\1)?[^><\'\"]*?)+(?:>|$)
将匹配所有 <> 对,忽略标记内引号内的右尖括号。因此,您希望匹配这些标签之外的所有内容。
可能有更好的方法来做到这一点,但您可以尝试以下想法:
- 匹配所有标签
- 对于每个标签,获取起始位置和长度 => 计算结束位置
- 将字符串的起始索引添加到结束位置的前面
- 将字符串的长度添加到起始位置
- 对于每个(结束,开始)对(因为我们正在反转匹配),运行替换方法并修改字符串。
String.prototype.spliceish = function(start, end, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(end);
};
var tagMatch = /<(?:[^><\"\']*?(?:([\"\']).*?\1)?[^><\'\"]*?)+(?:>|$)/g;
var tokenMatch = /\"([^\"]+)\"/g;
function invertedMatch(htmlString) {
var returnString = htmlString;
var startIndexes = [],
lengths = [],
match = tagMatch.exec(htmlString);
while(match !== null)
{
startIndexes.push(match.index);
lengths.push(match[0].length);
match = tagMatch.exec(htmlString);
}
var endIndexes = startIndexes.map(function(val, ix) { return val + lengths[ix]; });
var invertedStarts = [0].concat(endIndexes); // we are inverting, so capture start text.
var invertedEnds = startIndexes.concat(htmlString.length);
// will need to go backwards
for(var i = invertedStarts.length - 1; i >= 0; i--) {
var start = invertedStarts[i],
end = invertedEnds[i];
var stringReplace = htmlString.substring(start, end);
returnString = returnString.spliceish(start, end, stringReplace.replace(tokenMatch,
'<div class="gam-quotetext">"$1"</div>'));
};
return returnString;
}
$("#root").html(invertedMatch($("#root").html()));
.gam-quotetext{
color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="root">
<div class="gam-posttem">
<div class="gam-posttem1">
"quote here" and regular text here. "more quote here"
<br>
<br>
<a href="http://www.google.com">Link is Here</a>
</div>
</div>
</div>
关于javascript - 从 Javascript 中排除链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45205262/