Bold part of String

时间:2015-04-27 13:15:52

标签: javascript angularjs string

What is the best way to bold a part of string in Javascript?

I have an array of objects. Each object has a name. There is also an input parameter.

If, for example, you write "sa" in input, it automatically searches in array looking for objects with names that contain "sa" string.

When I print all the names, I want to bold the part of the name that coincide with the input text.

For example, if I search for "Ma":

Maria
Amaria
etc...

I need a solution that doesn't use jQuery. Help is appreciated.

PD: The final strings are in the

  • tag. I create a list using angular ng-repeat.

    This is the code:

    $scope.users = data;
                    for (var i = data.length - 1; i >= 0; i--) {
                      data[i].name=data[i].name.replace($scope.modelCiudad,"<b>"+$scope.modelCiudad+"</b>");
                    };
    

    ModelCiudad is the input text content var. And data is the array of objects.

    In this code if for example ModelCiudad is "ma" the result of each

  • is:

    <b>Ma</b>ria
    

    not Maria

  • 4 个答案:

    答案 0 :(得分:10)

    答案 1 :(得分:4)

    这是一个纯JS解决方案,它保留原始大小写(因此忽略了查询的大小写):

    const boldQuery = (str, query) => {
        const n = str.toUpperCase();
        const q = query.toUpperCase();
        const x = n.indexOf(q);
        if (!q || x === -1) {
            return str; // bail early
        }
        const l = q.length;
        return str.substr(0, x) + '<b>' + str.substr(x, l) + '</b>' + str.substr(x + l);
    }
    

    测试:

    boldQuery('Maria', 'mar'); // "<b>Mar</b>ia"
    boldQuery('Almaria', 'Mar'); // "Al<b>mar</b>ia"
    

    答案 2 :(得分:1)

    我今天遇到了类似的问题-除了我想匹配整个单词而不是子字符串。因此,如果比我想要的结果是const text = 'The quick brown foxes jumped'const word = 'foxes''The quick brown <strong>foxes</strong> jumped';但是如果是const word = 'fox',我预计不会有任何改变。

    我最终做了类似以下的事情:

    const pattern = `(\\s|\\b)(${word})(\\s|\\b)`;
    const regexp = new RegExp(pattern, 'ig'); // ignore case (optional) and match all
    const replaceMask = `$1<strong>$2</strong>$3`;
    
    return text.replace(regexp, replaceMask);
    

    首先,我得到在某个空格之前或之后或某个单词边界之前的确切单词,然后将其替换为相同的空格(如果有)和单词,但该单词被包装在<strong>中标签。

    答案 3 :(得分:1)

    这是我想出的一个版本,如果您想在react / javascript中为单词或单个字符的样式设置样式。

    replaceAt( yourArrayOfIndexes, yourString/orArrayOfStrings ) 
    

    工作示例:https://codesandbox.io/s/ov7zxp9mjq

    function replaceAt(indexArray, [...string]) {
        const replaceValue = i => string[i] = <b>{string[i]}</b>;
        indexArray.forEach(replaceValue);
        return string;
    }
    

    这是另一种替代方法

    function replaceAt(indexArray, [...string]) {
        const startTag = '<b>';
        const endTag = '</b>';
        const tagLetter = i => string.splice(i, 1, startTag + string[i] + endTag);
        indexArray.forEach(tagLetter);
        return string.join('');
    }
    

    还有一个...

    function replaceAt(indexArray, [...string]) {
        for (let i = 0; i < indexArray.length; i++) {
            string = Object.assign(string, {
              [indexArray[i]]: <b>{string[indexArray[i]]}</b>
            });
        }
        return string;
    }