例如,如果我有这个地址;
纽约第10大道820号,纽约10019
我想在regexp中匹配以下内容;
820第10大道
820第10大道
820第10大道纽约
以上是唯一预期的格式
到目前为止我的代码
var re = /(^\d*\D*\w*)/i;
var str = '820 10th Avenue New York, New York 10019';
它应该像这样工作;
if(re.test('820 10th Avenue')) console.log('pass'); // pass
if(re.test('820 10th Ave')) console.log('pass'); // pass
if(re.test('820 10th')) console.log('pass'); // pass
if(!re.test('820 9th Ave')) console.log('fail'); // fail
if(!re.test('820')) console.log('fail'); // fail
如果要检查输入字符串是否是给定字符串的一部分,可以使用String.prototype.indexOf()
:
var str = '820 10th Avenue New York, New York 10019';
str.indexOf('820 10th Avenue') > -1 // true
str.indexOf('820 10th Ave') > -1 // true
str.indexOf('820 10th') > -1 // true
str.indexOf('820 9th Ave') > -1 // false
str.indexOf('820') > -1 // true
更具体地说,与比较0
以查看是否为前缀:
var str = '820 10th Avenue New York, New York 10019';
str.indexOf('820 10th Ave') === 0 // true
str.indexOf('20 10th Ave') === 0 // false
根据给定的示例添加模式匹配:
function testAddress(input) {
var address = '820 10th Avenue New York, New York 10019';
var re = /^\d+(\s\w+){2,}/;
return re.test(input) && address.indexOf(input) === 0;
}
testAddress('820 10th Ave') // true
testAddress('820 10th Avenue') // true
testAddress('820 10th Avenue New York') // true
testAddress('820 9th Ave') // false
testAddress('820 10th') // false
testAddress('820') // false
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句