var keyword = 'test';
var replaced = $(".test-section").html().replace(new RegExp(keyword, "igm"),'<span class="greenbackground">'+keyword+'</span>');
$(".test-section").html(replaced);
我想突出显示我的段落的关键字。上面的代码运行良好,除非我的 div
内容中有 'testing'
,即使这样也能获取类。我怎样才能使我的代码仅针对特定字符串进行测试。请在fiddle上找到同样的问题
最佳答案
如果您对 JavaScript 对单词边界的定义感到满意,则可以使用 \b
:
var keyword = 'test';
var replaced = $(".test-section").html().replace(new RegExp("\\b" + keyword + "\\b", "igm"),'<span class="greenbackground">'+keyword+'</span>');
$(".test-section").html(replaced);
但是检查JavaScript's definition of a word character ,这可能会让你感到惊讶,它非常以英语为中心。具体来说,它是 26 个英文字母 A-Z(大小写)、数字 0-9 或下划线。根据 JavaScript,任何其他字符(例如 é
)都不是“单词”字符。
any alphanumeric character including the underscore. Equivalent to [A-Za-z0-9_].
如果您想应用自己的定义,您可以在捕获组中使用交替来测试“行开头或非单词字符”和“行结束或非单词字符”,并包含捕获的文本(如果有的话)在替换中。
var keyword = 'test';
var replaced = $(".test-section").html().replace(new RegExp("(^|\\W)" + keyword + "($|[^\\w])", "igm"),'$1<span class="greenbackground">'+keyword+'</span>$2');
$(".test-section").html(replaced);
在该示例中,对于“非单词字符的定义”,我使用了 \W
,这是 JavaScript 的“非单词字符”,但您当然想要调整它(否则,您只需使用前面显示的 \b
解决方案)。请注意替换开头的 $1
和末尾的 $2
- 这些是我们将单词前后匹配的字符(如果有)放回的位置.
如果你需要做一个无法用正则表达式表达的测试,你可以使用replace
上的函数回调:
var keyword = 'test';
var replaced = $(".test-section").html().replace(new RegExp("(^|.)" + keyword + "($|[^.])", "igm"), function(m, c1, c2) {
// Here, c1 will be the character before your keyword, or "" at beginning of line;
// c2 will be the character after your keyword, or "" at end of line.
// Return the new string to replace the match with.
// So for instance:
if (/*...your definition says c1 and c2 are not word characters...*/) {
// Update this occurrence:
return c1 + '<span class="greenbackground">'+keyword+'</span>' + c2;
} else {
// Leave it unchanged (in effect)
return m;
}
});
$(".test-section").html(replaced);
<小时/>
小心其中包含正则表达式专用字符的“关键字”。由于您使用的是 new RegExp
,如果您的关键字是(例如)$span
,那么它看起来就像行尾标记 $
后跟 span
。
关于javascript - 检查并仅用 javascript 替换 div 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24982323/