字符串正则表达式 replace/prepend

string regex replace/prepend

我需要将用户输入的字符串转换为搜索栏,这样我就可以在字符串中的任何单词前加上 "contactTags:",这不是特殊的搜索字符,例如 (,),AND,OR,不是这样搜索输入 (foo OR bar) AND baz NOT buz 变成 (contactTags:foo OR contactTags:bar) AND contactTags:baz NOT contactTags:buz

此字符串的最终用例是插入到 algolia 搜索的过滤器参数中。 (但实际上这个问题更多的是关于常规正则表达式字符串替换)

我可以生成一个让我接近的正则表达式模式,但我在字符串替换方面遇到问题:

const regex = /(?!OR|AND|NOT)\b[\w+]+\b/g;
let str = '(foo OR bar) AND baz NOT buz';


while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach(match => {
        str = str.replace(/(?!OR|AND|NOT)\b[\w+]+\b/,"contactTags:"+match)
    });
}

console.log(str)

不幸的是,这让我陷入困境:“(contactTags:foo:foo:foo:foo:foo:X10000 OR bar) AND baz NOT buz”

有什么想法吗?

谢谢!

您无需致电 exec 进行更换。只需这样调用 .replace

const regex = /\b(?!(?:OR|AND|NOT)\b)\w+\b/ig;
let str = '(foo OR bar) AND baz NOT buz';

str = str.replace(regex, 'contactTags:$&');

console.log(str);

const regex = /(?!OR|AND|NOT)\b([\w]+)\b/g;
let str = '(foo OR bar) AND baz NOT buz';

console.log(str.replace(regex, 'contactTags:'))