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.
1 Answer 1
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.
2 Comments
+ or [] as parts of the query will mess around with the regex if they're not properly escaped.query like: function replaceScapeChar(value) { return value.replace(/([\[|\]|\||\(|\)|\.|\*|\+|\{|\}|\$])/g, "\\1ドル") } (Maybe I didn't write ALL the scape characters. Add what I forgot :P)
queryinstead of&?querythen ... not the string inside variableit will search forString.prototype.replaceis a standard JavaScript function.