Xin Zhang
Xin Zhang

Reputation: 49

Javascript: How to replace all matching strings by html code

Here is my current code:

var filter = ['F', 'p'];
var table_data = ['F1', 'F-BAPP', 'ABC'];

table_data.forEach(function(d)
{
    var final_value = addClass(d, filter);
    console.log(final_value);
});

function addClass(text, filters)
{
    if (filters === '')
    {
        return text;
    }

    String.prototype.replaceAll = function(FindText, RepText)
    {
        regExp = new RegExp(FindText, "gi");
        return this.replace(regExp, RepText);
    };

    filters.forEach(function(kw)
    {
        text = (text + "").replaceAll(kw, "<span class='_p-filter-matched'>" + kw + "</span>");
    });

    return text;
}

I want the final_value's output to be like this:

<span class='_p-filter-matched'>F</span>1
<span class='_p-filter-matched'>F</span>-BA<span class='_p-filter-matched'>P</span><span class='_p-filter-matched'>P</span>

But there are two questions:

 1. <span> becomes <s<span class='_p-filter-matched'>p</span>an.

 2. F-BAPP becomes f-BApp. 

So, what should I do? Thank you all.

Upvotes: 0

Views: 249

Answers (1)

Shidersz
Shidersz

Reputation: 17190

Your main problem is because you are iterating over the filter array and do a replacement one a time. So when you replace F by "<span class='_p-filter-matched'>" + kw + "</span>" you are adding multiple p characters on the string that the next filter p will going to replace.

On the next approach, I have used the function as second parameter (function(replacement)) of the replace() method to do all the replacements on one shot using also a regular expression that will look for all the filters (example: the regular expression F|p).

Approach:

var filter = ['F', 'p'];
var table_data = ['F1', 'F-BAPP', 'ABC'];

table_data.forEach(function(d)
{
    var final_value = addClass(d, filter);
    console.log(final_value);
});

function addClass(text, filters)
{
    if (!filters.length)
        return text;

    String.prototype.replaceAll = function(filters, RepText, token)
    {
        regExp = new RegExp(filters.join("|"), "gi");

        return this.replace(regExp, (match) =>
        {
           return RepText.replace(token, match);
        });
    };

    let repText = "<span class='_p-filter-matched'>*filter*</span>";
    let token = "*filter*";

    return text.replaceAll(filters, repText, token);
}

Upvotes: 1

Related Questions