How can i add more variables to this?

Hi,

I have the following script which highlights some text, e.g 10%, but I want it to also highlight other text e.g 15%. At the moment, it only highlights the 10%. How can I make it highlight other words?

var text = '15% off';
    var text = '10% off';

$( 'li' ).html( function ( i, html ) {
    var regexp, replacement;

    regexp = RegExp( '(' + text + ')', 'gi' );
    replacement = '<span class="highlight">$1</span>';

    return html.replace( regexp, replacement );
});

Not sure I understand what you are asking for. Do you want to do something for various percentages?

I don’t know JavaScript, but it seems to me that maybe you could use a CASE statement, or a series of IF-THEN-ELSEs…

In PHP you would do this…

switch (n){
    case label1:
        code to be executed if n=label1;
        break;

    case label2:
        code to be executed if n=label2;
        break;

    case label3:
        code to be executed if n=label3;
        break;

    default:
        code to be executed if n is different from all labels;
}

Part of the problem is (according to the sample code you provided) that you are declaring the variable ‘text’ twice (declare, set value, declare again, change value.) Once a variable is declared, declaring it any more times will result in an error. You should see an error message in your console.

HTH,

:slight_smile:

1 Like

Put them in an array and join them with a bar, which means “or” in regular expressions.

var findText = ['15% off', '10% off'];

$( 'li' ).html( function ( i, html ) {
    var regexp, replacement;
    regexp = RegExp( '(' + findText.join('|') + ')', 'gi' );
    replacement = '<span class="highlight">$1</span>';
    return html.replace( regexp, replacement );
});

Here’s the result: http://jsfiddle.net/13zstd9c/

1 Like

Your code is using text in a regular expression so to test for both 10 and 15% all you need is:

var text = '1[05]% off';

for any other combination of strings to test for you just need to set up an appropriate regular expression.

And as soon as they want to change it to something else, like 20% or 5%, it becomes unmanageable again. :smile:

1 Like

How about just checking for (\d+% off) which captures all numeric percentage off values?
See it in action at http://jsfiddle.net/pmw57/31p845a4/2/

Thanks man, this is the answer I needed - I thought in the back of my mind an array, but didn’t know how. Many thanks for you help!

1 Like

Well, what if you don’t want to highlight 5% or 20%?

I guess it depends on the use.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.