简体   繁体   English

使用变量替换所有出现的特定字符串

[英]Use variable to replace all occurrences of specific string

How do I use a dynamic variable as first argument in replace function? 如何在replace函数中使用动态变量作为第一个参数?

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. replace(/&/g, '<strong>$&</strong>'))不起作用。

I want to wrap all occurrences of query with <strong> tags. 我想用<strong>标签包装所有出现的query

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 . 当您在html中搜索任意值时,您需要创建一个RegExp对象并将其用于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 ) (来自MDN

See Regular Expressions at Mozilla Developer Network for a more in depth discussion on regular expressions. 有关正则表达式的更深入讨论,请参见Mozilla开发人员网络上的正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM