Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 正则表达式替换的问题_Javascript_Regex - Fatal编程技术网

Javascript 正则表达式替换的问题

Javascript 正则表达式替换的问题,javascript,regex,Javascript,Regex,我试图突出使用regex和css传递的单词。但似乎出了问题。有人能帮我吗$1在这里似乎不起作用,因为它不能替换为单词 <head> <title>Example</title> <style type="text/css"> .highlight{ color: maroon; font-size: 22px; } </style> <script type="text/javascript" src

我试图突出使用regex和css传递的单词。但似乎出了问题。有人能帮我吗$1在这里似乎不起作用,因为它不能替换为单词

 <head>
<title>Example</title>

<style type="text/css">
  .highlight{
    color: maroon;
    font-size: 22px;
  }

</style>
<script type="text/javascript" src="../scripts/jquery-1.4.js"></script>
<script type="text/javascript">
function getSentence(word) {
var sentence="here is the text";

if (sentence.toLowerCase().indexOf(word.toLowerCase())!=-1) {
    sentence=sentence.replace(new RegExp('\\b'+(word)+'\\b', 'g'), '<span class="highlight">\$1</span>');

    $("#placeholder").append("<h3>"+sentence+"</h3><br/>");

    }
    }
</script>

实例
.亮点{
颜色:栗色;
字体大小:22px;
}
功能语句(词){
var station=“这是文本”;
if(句子.toLowerCase().indexOf(word.toLowerCase())!=-1){
句子=句子。替换(新的RegExp('\\b'+(word)+'\\b',g'),'\$1');
$(“#占位符”)。追加(“+句子+”
); } }


文本

您没有设置任何捕获组,因此在替换方法中应该使用
$&
而不是
$1


正则表达式中的捕获括号位于错误的位置。现在括号消失了,因为它们不是文字,而只是一个分组函数。如果将括号放在引号中,则正则表达式应该可以工作,如下所示:

'\\b(' + word + ')\\b'
'\\b(' + word + ')\\b'