Bold part of String

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"

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.


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.