嗨,我有一个 Javascript 函数,可以替换大海捞针中的针,因为您会看到大海捞针是页面的整个主体。
function replace(needle, replacement) {
haystackText = document.body.innerHTML
var match = new RegExp(needle, "ig");
var replaced = "";
replaced = haystackText.replace(match, replacement);
document.body.innerHTML = replaced;
}
我的问题是我正在寻找的针不准确。例如,为了方便起见,我会说针文本是“foo”。我想要替换的文本可能如下所示。
Here is some example text abcfooxyz, that is all.
我需要替换 abcfooxyz,但我只知道要查找的内容是 foo。因此,如果替换文本是 bar,我需要输出如下所示。
Here is some example text bar that is all.
如果这很明显,我很抱歉我已经寻找了解决方案,但 javascript 不是我的母语,但我被迫使用它来实现这个应用程序。我可以使用 jQuery,但我不想使用,因为我还没有调用该库,而且我不太了解它。
感谢您的帮助。
编辑:找到解决方案
好的,在对 RegExp 进行一些额外的阅读和实验之后,我编写了一个单独的函数来处理 a href html 标签内的 URL。这用于在继续使用 rel="noreferrer"继续和停止引用和页面排名数据流之前,将单击出站链接的用户重定向到警告页面。这里的 bdy 是 java 脚本 documnet.body.innerHTML 元素。
function linkreplace(link, bdy) {
haystackText = bdy;
var replacement = 'a href=\"http://mysite.com/outbound_refer.php?link=' + link + '\" rel=\"noreferrer\"';
var match = new RegExp('[^\\<\\>]*' + link + '[^\\>\\<]*', 'ig');
replaced = haystackText.replace(match, replacement);
return replaced;
}
这里 RegExp 查找针文本并包含 HTML 标记内的所有文本,直到找到打开和关闭的标记。这里\< 和\> 设置表达式来查找 < 和 > 的特殊字符,因此常规文本中的 <> 不会匹配。 ^ 将表达式设置为匹配除括号中的字符之外的所有字符。
最佳答案
试试这个:
var match = new RegExp('(\\b)\\w*' + needle + '\\w*(\\b)', 'ig');
haystackText.replace(match, '$1' + replacement + '$2');
正则表达式的解释:
\b word boundary (space, punctuation, etc) \w* 0 or more alphanumeric characters [needle] your text \w* 0 or more alphanumeric characters \b word boundary
关于javascript - 更换干草堆中不精确的针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7047705/