简体   繁体   English

在javascript中使用正则表达式找到字符串末尾的匹配项

[英]find the match at end of the string using regex in javascript

I have a string for ex "adlkup.db.com" and I want to validate the string for ".com" at the end of the string. 我有一个用于"adlkup.db.com"的字符串,我想在字符串末尾验证“ .com”的字符串。

var x = "adlkup.db.com";

So I am trying something like 所以我正在尝试类似

/.com$/.test(x)

and the . . is interpreting to some other regex which finds a single character, except newline or line terminator 正在解释其他找到单个字符的正则表达式,换行符或行终止符除外

A period in a regular expression matches any character. 正则表达式中的句点与任何字符匹配。

To make it literal, you need to escape it: 要使其字面值,您需要对其进行转义

/\.com$/.test('stackoverflow.com'); // true
/\.com$/.test('stackoverflowcom');  // false

Alternatively, as Racil Hilan points out in the comments , you can also use the .lastIndexOf() method in order to check: 另外,正如Racil Hilan在评论中指出的那样 ,您还可以使用.lastIndexOf()方法来检查:

var string = 'stackoverflow.com';
string.lastIndexOf('.com') === string.length - 4; // true

or using the .substr() method : 或使用.substr()方法

'stackoverflow.com'.substr(-4) === '.com'; // true

In ECMAScript 6 this is done with endsWith : 在ECMAScript 6中,这是使用endsWith完成的:

x.endsWith(".com");

There is a polyfill for old browsers. 旧的浏览器有一个polyfill

After reading your comments, I think you can use this better than the regex: 阅读您的评论后,我认为您可以比正则表达式更好地使用它:

 var value1 = "adlkup.db.com"; var value2 = "adlkup.db.com.w3Schools"; var value3 = ".com"; document.write(value1 + " " + endWithCom(value1) + "<br/>"); document.write(value2 + " " + endWithCom(value2) + "<br/>"); document.write(value3 + " " + endWithCom(value3) + "<br/>"); function endWithCom(text){ if(text.length < 5) return false; return (text.substr(-4) == ".com"); } 

And you can easily convert it to generic function so you can pass it any ending you want to check: 您可以轻松地将其转换为泛型函数,以便将想要检查的任何结尾都传递给它:

 var value1 = "adlkup.db.com"; var value2 = "adlkup.db.com.w3Schools"; var value3 = ".com"; var value4 = "adlkup.db.org"; document.write(value1 + " " + endWithButNotEqual(value1, ".com") + "<br/>"); document.write(value2 + " " + endWithButNotEqual(value2, ".com") + "<br/>"); document.write(value3 + " " + endWithButNotEqual(value3, ".com") + "<br/>"); document.write(value4 + " " + endWithButNotEqual(value4, ".org") + "<br/>"); function endWithButNotEqual(text, ending){ if(text.length <= ending.length) return false; return (text.substr(-ending.length) == ending); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM