簡體   English   中英

使用JavaScript中的捕獲組從變量創建正則表達式

[英]Create regex from variable with capture groups in javascript

如何從變量創建正則表達式,使其具有捕獲組,然后可以在replace()調用中使用它?

以下是到目前為止我沒有嘗試過的嘗試。

 var term = 'test' var r = new RegExp('('+term+')', "ig"); $('#test').html( $('#test').html().replace(r, '<span class="found">'+$1+'</span>') ); // Uncaught ReferenceError: $1 is not defined 
 .found{ background-color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="test">This is a test</div> 

我想這按預期工作嗎? 最主要的是在替換字符串中使用$1 ,如<span class="found">$1</span>

 var term = 'test' var r = new RegExp('('+term+')', "ig"); $('#test').html( $('#test').html().replace(r, '<span class="found">$1</span>') ); 
 .found{ background-color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="test">This is a test</div> 

您還可以丟棄捕獲組,並在引用整個匹配項的字符串替換模式中使用$& backreference ,並轉義搜索字符串,因為萬一其中包含特殊的正​​則表達式字符 ,則可能無法匹配:

 var term = 'test+test' var r = new RegExp(term.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'), "ig"); $('#test').html( $('#test').html().replace(r, '<span class="found">$&</span>') ); 
 .found{ background-color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="test">This is a test+test</div> 

您需要用函數包裝替換表達式。

 var term = 'test' var r = new RegExp('('+term+')', "ig"); $('#test').html( $('#test').html().replace(r, function($1){return '<span class="found">'+$1+'</span>'}) ); // Uncaught ReferenceError: $1 is not defined 
 .found{ background-color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="test">This is a test</div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM