Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bold part of 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

  • like image 401
    Phyron Avatar asked Apr 27 '15 13:04

    Phyron


    People also ask

    How do I make part of a string bold in HTML?

    To bold the text in HTML, use either the strong tag or the b (bold) tag. Browsers will bold the text inside both of these tags the same, but the strong tag indicates that the text is of particular importance or urgency. You can also bold text with the CSS font-weight property set to “bold.”

    How do I make part of a string bold in Java?

    16 + names. length() is where to stop bolding. So I said start bolding after "You have chosen " and stop bolding the length of the name positions after where it started. b is the type of span to apply on the StringBuilder (which is bold).

    How do I make part of a string bold in C#?

    var result = this. formaatedstring(Final, stringA);


    Video Answer


    4 Answers

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

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

    The above will only replace the first instance of substr. If you want to handle replacing multiple substrings within a string, you have to use a regular expression with the g modifier.

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

    In practice calling boldString would looks something like:

    boldString("Hello, can you help me?", "el"); 
    // Returns: 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?

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


    A concise ES6 solution could look something like this:

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

    Where str is the string you want to modify, and substr is the substring to bold.


    ES12 introduces a new string method str.replaceAll() which obviates the need for regex if replacing all occurrences at once. It's usage in this case would look something like this:

    const boldString = (str, substr) => str.replaceAll(substr, `<b>${substr}</b>`);
    

    I should mention that in order for these latter approaches to work, your environment must support ES6/ES12 (or use a tool like Babel to transpile).

    Another important note is that all of these approaches are case sensitive.

    like image 96
    Mike Hamilton Avatar answered Oct 05 '22 02:10

    Mike Hamilton


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

    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"
    
    like image 30
    Geo Avatar answered Oct 05 '22 02:10

    Geo


    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.

    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 = `$1<strong>$2</strong>$3`;
    
    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.

    like image 41
    gilmatic Avatar answered Oct 05 '22 03:10

    gilmatic


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

    replaceAt( yourArrayOfIndexes, yourString/orArrayOfStrings ) 
    

    Working example: 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;
    }
    
    like image 28
    Matt Wright Avatar answered Oct 05 '22 04:10

    Matt Wright