Javascript 字符串的粗体部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29896907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:16:59  来源:igfitidea点击:

Bold part of String

javascriptangularjsstring

提问by Phyron

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

在 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.

例如,如果您在输入中写入“sa”,它会自动在数组中搜索名称中包含“sa”字符串的对象。

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":

例如,如果我搜索“Ma”:

Maria
Amaria
etc...

RIA
一个MARIA
等..

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

我需要一个不使用 jQuery 的解决方案。帮助表示赞赏。

PD: The final strings are in the

PD:最后的字符串在

  • 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

  • 标签。我使用 angular ng-repeat 创建了一个列表。

    这是代码:

    $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 是输入文本内容变量。而数据是对象数组。

    在此代码中,如果例如 ModelCiudad 是“ma”,则每个

  • is:

    <b>Ma</b>ria
    

    not Maria

  • 是:

    <b>Ma</b>ria
    

    没有RIA

  • 回答by Michael Hamilton

    You can use Javascript's str.replace()method, where stris equal to all of the text you want to search through.

    您可以使用 Javascript 的str.replace()方法,其中str等于您要搜索的所有文本。

    var str = "Hello";
    var substr = "el";
    str.replace(substr, '<b>' + substr + '</b>');
    

    If you want to handle replacing multiple substrings within a string, you have to use a regular expression with the gmodifier.

    如果要处理替换字符串中的多个子字符串,则必须使用带有g修饰符的正则表达式。

    function boldString(str, substr) {
      var strRegExp = new RegExp(substr, 'g');
      return str.replace(strRegExp, '<b>'+substr+'</b>');
    }
    

    Calling boldString("Hello, can you help me?", "el")will return: H<b>el</b>lo can you h<b>el</b>p me?

    调用boldString("Hello, can you help me?", "el")将返回: H<b>el</b>lo can you h<b>el</b>p me?

    Which when rendered by the browser will look something like: Hello can you help me?

    当通过浏览器呈现看起来像:H EL罗可你^ h ELp我吗?

    Here is a JSFiddle with an example: https://jsfiddle.net/1rennp8r/3/

    这是一个带有示例的 JSFiddle:https://jsfiddle.net/1rennp8r/3/



    Happened to come back across this old answer and figured I'd update with a concise ES6 solution :)

    碰巧回到这个旧答案,并认为我会用简洁的 ES6 解决方案进行更新:)

    const boldString = (s, b) => s.replace(RegExp(b, 'g'), `<b>${b}</b>`);
    

    Where sis the string you want to modify, and bis the substring to bold.

    s要修改的字符串在哪里,b要加粗的子字符串在哪里。

    回答by Geo

    Here's a pure JS solution that preserves the original case(ignoring the case of the query thus):

    这是一个保留原始大小写的纯 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);
    }
    

    Test:

    测试:

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

    回答by gilmatic

    I ran into a similar problem today - except I wanted to match whole words and not substrings. so if const text = 'The quick brown foxes jumped'and const word = 'foxes'than I want the result to be 'The quick brown <strong>foxes</strong> jumped'; however if const word = 'fox', than I expect no change.

    我今天遇到了类似的问题 - 除了我想匹配整个单词而不是子字符串。所以如果const text = 'The quick brown foxes jumped'并且const word = 'foxes'比我想要的结果是'The quick brown <strong>foxes</strong> jumped'; 但是,如果const word = 'fox',比我预期的没有变化。

    I ended up doing something similar to the following:

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

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

    First I get the exact word which is either before/after some whitespace or a word boundary, and then I replace it with the same whitespace (if any) and word, except the word is wrapped in a <strong>tag.

    首先,我得到在一些空格或单词边界之前/之后的确切单词,然后我用相同的空格(如果有)和单词替换它,除了单词被包裹在<strong>标签中。

    回答by Matt Wright

    Here is a version I came up with if you want to style words or individual characters at their index in react/javascript.

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

    replaceAt( yourArrayOfIndexes, yourString/orArrayOfStrings ) 
    

    Working example: https://codesandbox.io/s/ov7zxp9mjq

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

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

    And here is another alternate method

    这是另一种替代方法

    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('');
    }
    

    And another...

    还有一个...

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