2

How do I use a dynamic variable as first argument in replace function?

I have this code that searches a user specified string:

 var query = jQuery.trim(jQuery(this).val()).toLowerCase();
 console.log(query + ' was searched')
 jQuery('.one-reference').each(function () {
    var jQuerythis = jQuery(this);
    if (jQuerythis.text().toLowerCase().indexOf(query) === -1) {
       jQuerythis.fadeOut();
    }
    else {
       jQuerythis.html(jQuerythis.html().replace(/&/g, '<strong>$&</strong>'));
       jQuerythis.fadeIn();
    }
 });

This replace(/&/g, '<strong>$&</strong>')) is not working.

I want to wrap all occurrences of query with <strong> tags.

4
  • can you create a fiddle demonstrating the issue? Commented Nov 28, 2016 at 14:44
  • Shouldn't you then search for query instead of &? Commented Nov 28, 2016 at 14:46
  • @Stefan it will search for the sting query then ... not the string inside variable it will search for Commented Nov 28, 2016 at 14:50
  • FYI: your problem is unrelated to jQuery. String.prototype.replace is a standard JavaScript function. Commented Nov 28, 2016 at 15:26

1 Answer 1

3

As you're searching for an arbitrary value within the html you will need to create a RegExp object and use that in your replace.

if (jQuerythis.text().toLowerCase().indexOf(query) === -1) {

  jQuerythis.fadeOut();
} else {
  var queryReg = new RegExp(query, 'g');
  jQuerythis.html(jQuerythis.html().replace(queryReg, '<strong>$&</strong>'));
  jQuerythis.fadeIn();
}

Also you will first need to escape (\) any characters in your query variable that have a special meaning in regular expressions (^$[]+()\/- for example) -

query = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

(from MDN)

See Regular Expressions at Mozilla Developer Network for a more in depth discussion on regular expressions.

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

2 Comments

Be sure to mention that inputting + or [] as parts of the query will mess around with the regex if they're not properly escaped.
He could also use a function to clean the string query like: function replaceScapeChar(value) { return value.replace(/([\[|\]|\||\(|\)|\.|\*|\+|\{|\}|\$])/g, "\\$1") } (Maybe I didn't write ALL the scape characters. Add what I forgot :P)

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.