js正则表达式使用变量
2017-03-22 18:56
344 查看
业务背景:
1. 搜索未开通业务的公司。数据量不到100条, 数据是通过恒生t2接口拿到,拿到数据后还要在Java中去做匹配,索性就在js中匹配,但是变量不能直接用到正则表达式中,所以使用正则表达式的构造函数生成正则。
js:
// ---------完全匹配词语,所以不能匹配单个字--------------
var name = "中登"; // 要匹配到变量
var reg =new RegExp(name);
var result = reg.test("证券市场中登公司是大哥");
console.log(result); // true
result = reg.test("中国登记结算有限公司的股份由上交所、深交所各持一半");
console.log(result); //false
// ----------匹配开头---------------
reg = new RegExp("^"+name)
result = reg.test("中登公司是证券市场大哥");
console.log(result); // true
result = reg.test("证券市场中登公司是大哥");
console.log(result); // false
result = reg.test("证券市场大哥是中登");
console.log(result); //false
// ---------匹配结束------------------------
reg = new RegExp(name+"$");
result = reg.test("中登公司是证券市场大哥");
console.log(result); // false
result = reg.test("证券市场中登公司是大哥");
console.log(result); //false
result = reg.test("证券市场大哥是中登");
console.log(result); // true
1. 搜索未开通业务的公司。数据量不到100条, 数据是通过恒生t2接口拿到,拿到数据后还要在Java中去做匹配,索性就在js中匹配,但是变量不能直接用到正则表达式中,所以使用正则表达式的构造函数生成正则。
js:
// ---------完全匹配词语,所以不能匹配单个字--------------
var name = "中登"; // 要匹配到变量
var reg =new RegExp(name);
var result = reg.test("证券市场中登公司是大哥");
console.log(result); // true
result = reg.test("中国登记结算有限公司的股份由上交所、深交所各持一半");
console.log(result); //false
// ----------匹配开头---------------
reg = new RegExp("^"+name)
result = reg.test("中登公司是证券市场大哥");
console.log(result); // true
result = reg.test("证券市场中登公司是大哥");
console.log(result); // false
result = reg.test("证券市场大哥是中登");
console.log(result); //false
// ---------匹配结束------------------------
reg = new RegExp(name+"$");
result = reg.test("中登公司是证券市场大哥");
console.log(result); // false
result = reg.test("证券市场中登公司是大哥");
console.log(result); //false
result = reg.test("证券市场大哥是中登");
console.log(result); // true
相关文章推荐
- JS字符串替换函数全部替换方法 JS 正则表达式如何使用变量
- JS字符串替换函数全部替换方法 JS 正则表达式如何使用变量
- js(replace)正则表达式中如何使用变量?
- JS中的正则表达式小小的技巧---Test方法的使用
- 简单的正则表达式在JS中的使用
- ASP.NET 使用CustomValidator调用js函数动态修改验证TextBox的正则表达式,无刷新
- JS 和 C#使用正则表达式
- 在JS中使用正则表达式验证电子邮箱是否正确
- 含有变量的正则表达式使用方法
- 正则表达式的在java、js、jsp中的使用
- JS中正则表达式的使用
- 正则学习之一:在js中使用正则表达式
- js正则表达式使用
- javascript正则表达式中使用变量关键字
- Java/Js下使用正则表达式匹配嵌套Html标签
- JS中的正则表达式小小的技巧---Test方法的使用
- 在Js中使用正则表达式验证输入时的注意点
- 在JS使用正则表达式屏蔽敏感字符
- JS中match方法中使用正则表达式