簡體   English   中英

如何在正則表達式中使用變量並操作變量?

[英]How do you use a variable in a regular expression and manipulate the variable?

我想使用RegExp創建一個替換 function 。 到目前為止,我已經做了這樣的事情。

var re = new RegExp(FullName);
testBox2.value = testBox2.value.replace(/re.{13}/g," "); 

所以基本上我想傳遞FullName然后使用該全名想刪除fullNamefullName之后的 13 個字符。 但是這段代碼似乎不起作用。

以前我做過這個,效果很好。

testBox.value =  testBox.value.replace(FullName," ");  

當你想在正則表達式中使用變量時,你必須像這樣使用new關鍵字:

const stringToReplace = 'NameHere';
const regex = new RegExp(`${stringToReplace}.{13}`,'g');

完整的工作示例:

const string = 'LeaveThisBitNameHereExtraStuffToo123'; 
const stringToReplace = 'NameHere'; 
const regex = new RegExp(`${stringToReplace}.{13}`,'g'); 
const res = string.replace(regex, ''); 
console.log(res); // -> LeaveThisBit123

您可以創建一個 util function 來編寫正則表達式:

function composeRegexp(a, b) {
    if (a instanceof RegExp) {
      a = a.toString().replace(/^\//, '').replace(/\/$/, '');
    }
    if (b instanceof RegExp) {
      b = b.toString().replace(/^\//, '').replace(/\/$/, '');
    }
    return new RegExp(a + b);
}

並像這樣使用它:

const composed = composeRegexp(FullName, '.{13}');

例子:

 function composeRegexp(a, b) { if (a instanceof RegExp) { a = a.toString().replace(/^\//, '').replace(/\/$/, ''); } if (b instanceof RegExp) { b = b.toString().replace(/^\//, '').replace(/\/$/, ''); } return new RegExp(a + b); } const composed = composeRegexp(new RegExp('a'), '{3}'); console.log(composed.test('aaa')); console.log(composed.test('abc'));

假設您有一個輸入文本框(以及一個用於測試的 output 框):

<input id="testBox2" type="text" value="Hello Joe Bloggs, how are you doing today?"/>

<div id="output">result</div>

我們可以使用 javascript 訪問這兩個元素:

var testBox2 = document.getElementById('testBox2');
var output = document.getElementById('output');

然后我們可以像這樣替換任何指定的 fullName 和它后面的 13 個字符:

var fullName = 'Joe Bloggs';

var regex = new RegExp(fullName+'.{13}', 'ig');
output.innerHTML = testBox2.value.replace(regex, '');

這是工作小提琴https://jsfiddle.net/anandamasri/4whb9mc1/37/

暫無
暫無

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

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