javascript - 检查并仅用 javascript 替换 div 字符串

标签 javascript string replace

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);

Updated Fiddle

但是检查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/

相关文章:

javascript - 匹配时提取字符串

javascript - 定义了一个可以作为对象调用的函数

c++ - 未使用某些文字读取输入

javascript - 获取 JSON 键的文本值

regex - 无法通过子例程通过正则表达式替换字符串

JavaScript - 在第一个图像周期结束时加载第二个图像帧

javascript - 使用 Ajax post 的奇怪行为,但在 html 提交更改后允许 GET 和 Head

python - 替换某些索引处的字母

PHP用数组变量替换字符串中的{var ['key' ]}

javascript - 如何用 JavaScript 替换 HTML 文档中损坏的图像?