[英]JavaScript regex.exec() should intended to use an assembled regEx
如果我使用( https://jsfiddle.net/fgsvzn4a/ ):
var text = "ui1pu";
var regExParameter = '\d+';
var regEx = '/(.*)' + regExParameter + '(.*)/gi';
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
console.log(newStr);
}
我收到此錯誤:
Paused on exception
TypeError: regEx.exec is not a function
這個原型正在工作(受https://stackoverflow.com/a/15845184/2891692啟發):
var text = "my1bla"; var matches = /(my)\d+(.*)/gi.exec(text); if(matches && matches[1]) { var str1 = matches[1]; var str2 = matches[2]; var newStr = str1 + str2 alert(newStr); }
但我想使用輸入參數來構建正則表達式(第一個例子)。
我得到ReferenceError: Regex is not defined
如果我嘗試這個:
var text = "ui1pu";
var regExParameter = '\d+';
var regExString = '/(.*)' + regExParameter + '(.*)/gi';
var regEx = new Regex(regExString);
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
console.log(newStr);
}
任何想法?
使用RegExp
構造函數。 請注意,應從字符串中省略斜杠,並且應將標志作為第二個參數傳遞。
var text = "ui1pu"; var regExParameter = '\\d+'; var regExString = '(.*)' + regExParameter + '(.*)'; var regEx = new RegExp(regExString, 'gi'); var matches = regEx.exec(text); if(matches && matches[1]) { var str1 = matches[1]; var str2 = matches[2]; var newStr = str1 + str2 console.log(newStr); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.