简体   繁体   English

在javascript中,如何在不覆盖以前的粗体字符串的情况下用粗体文本替换多个字符串?

[英]In javascript, how do I replace multiple strings with bold text without overriding the previous bold string?

function replaceKeys(inputString, keys){

    for (var i = 0; i < keys.length; i++) {
                var t = keys[i];
                if (t) inputString= inputString.replace(new RegExp(t, 'gi'), '<strong>' + t + '</strong>');
            }
            return s;
}  

With the javascript method above I have tried to bold all text in a given string, based on a list of "keys" or string parts. 使用上面的javascript方法,我已尝试根据“键”或字符串部分的列表将给定字符串中的所有文本加粗。

Example inputs: 输入示例:
keys=["man", "str"] inputString="strong man" keys = [“ man”,“ str”] inputString =“ strong man”
intended output : 预期输出
str ong man 海峡的人

Unfortunately the output is replacing the "str" parts of the strong tags too. 不幸的是,输出也替换了强标签的“ str”部分。 Meaning the output becomes 意味着输出变为

< str ong> str strong>ong man . < str ong> str strong> ong man
Is there a Regular expression or some other method so that I can ignore html tags in a string so it doesn't have weird behaviour like this? 是否有正则表达式或其他方法,以便我可以忽略字符串中的html标签,因此它没有像这样的怪异行为?

You can do this by defining a placeholder instead of using <strong> tags directly: 您可以通过定义一个占位符而不是直接使用<strong>标签来做到这一点:

function replaceKeys(inputString, keys){
    var placeholder = '!!';
    var s = inputString.replace(new RegExp(/strong>/gi),placeholder);
    for (var i = 0; i < keys.length; i++) {
                var t = keys[i];
                if (t) s = s.replace(new RegExp(t, 'gi'), '<' + placeholder + t + '</' + placeholder );
            }
            return s.replace(new RegExp(placeholder,'g'),'strong>');
} 
replaceKeys("strong man",["man", "str"]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM