RegExpr and variable
RegExpr and variable
我只有一个问题,也许很愚蠢(就像每天一样)
var word = []; (an array with 100 words for example)
var tab = []; // resultat
var root = "test";
var debut = "Anti";
var reg1=new RegExp("^"+debut + "+." + root,"g")
for(var i = 0;i<word.length; i++){
// a word begin with Anti and contain test pls
if (word[i].match(reg1)){´
tab.push(word[i])
}
}
console.log(tab.join(', ');
但它不起作用,我不知道如何在正则表达式中使用变量,谢谢,对不起我的英语
var r = new RegExp('anti.*esis', 'ig')
document.write('antithesis'.match(r), '<br/>') // ["antithesis"]
document.write('antihero'.match(r), '<br/>') // null
这是代码,但使用的是test()而不是match()
var word=["yea","antiboyahtest","antigssjshbztest"];
var debut="anti";
var root="test";
var reg=new RegExp("^"+debut+".*"+root,"g");
var tabs=[];
for(i in word){
if(reg.test(word[i])){
tabs.push(word[i]);
}
}
alert(tabs);
使用 RegExp.test
和 Array.filter
函数的解决方案:
var word = ['Antitest', 'Antidot', 'Anti-next-test', 'testAnti'],
root = "test", debut = "Anti",
reg1 = new RegExp("^"+debut + ".*?" + root, "g");
var result = word.filter(function (w) {
return reg1.test(w);
});
console.log(result); // ["Antitest", "Anti-next-test"]
此外,还有一种使用Array.indexOf
没有任何正则表达式的函数的附加方法,它将给出相同的结果:
...
var result = word.filter(function (w) {
return w.indexOf(debut) === 0 && w.indexOf(root) !== -1;
});
相关文章:
- Selenium WebDriver and JavaScript change
- 从jQuery调用存储在Variable中的函数
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- 将Transform和Instance Variable转换为对象的JavaScript数组
- javascript setInterval() and Variable Scope
- Variable JS and PHP,
- C# and Javascript Variable
- Dojo Tooltip Spring and variable
- jquery ajax send form.serialize, variable and array all as d
- RegExpr and variable
- JavaScript variable and Smarty