gpt4 book ai didi

javascript - JS - 使用正则表达式获取字符串替换的原始值

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:08:12 26 4
gpt4 key购买 nike

我们有一个字符串:

var dynamicString = "This isn't so dynamic, but it will be in real life.";

一些输入的用户类型:

var userInput = "REAL";

我想匹配这个输入,并用 span 包裹它以突出显示它:

var result = " ... but it will be in <span class='highlight'>real</span> life.";

所以我使用一些 RegExp 魔术来做到这一点:

// Escapes user input,
var searchString = userInput.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

// Now we make a regex that matches *all* instances
// and (most important point) is case-insensitive.
var searchRegex = new RegExp(searchString , 'ig');

// Now we highlight the matches on the dynamic string:
dynamicString = dynamicString.replace(reg, '<span class="highlight">' + userInput + '</span>');

这一切都很好,除了这里是结果:

console.log(dynamicString);
// -> " ... but it will be in <span class='highlight'>REAL</span> life.";

我用用户的输入替换了内容,这意味着文本现在不区分大小写。

如何用上面显示的范围包装所有匹配项,同时保持匹配项的原始值?

想通了,理想的结果是:

// user inputs 'REAL',

// We get:
console.log(dynamicString);
// -> " ... but it will be in <span class='highlight'>real</span> life.";

最佳答案

您将使用正则表达式捕获组和反向引用来捕获匹配并将其插入到字符串中

var searchRegex = new RegExp('('+userInput+')' , 'ig');
dynamicString = dynamicString.replace(searchRegex, '<span class="highlight">$1</span>');

FIDDLE

关于javascript - JS - 使用正则表达式获取字符串替换的原始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20819541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com