0

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.

1
  • 3
    Can you please clarify what you're even trying to do? Please edit your question. Commented Jan 23, 2019 at 3:56

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.