[英]Regex string ends with not working in Javascript
I am not very familiar with regex.我对正则表达式不是很熟悉。 I was trying to test if a string ends with another string.
我试图测试一个字符串是否以另一个字符串结尾。 The code below returns null when I was expecting true.
当我期望为真时,下面的代码返回 null。 What's wrong with the code?
代码有什么问题?
var id = "John";
var exists ="blahJohn".match(/id$/);
alert(exists);
Well, with this approach, you would need to use the RegExp
constructor , to build a regular expression using your id
variable:好吧,使用这种方法,您需要使用
RegExp
构造函数,使用您的id
变量构建正则表达式:
var id = "John";
var exists = new RegExp(id+"$").test("blahJohn");
alert(exists);
But there are plenty ways to achieve that, for example, you can take the last id.length
characters of the string, and compare it with id
:但是有很多方法可以实现这一点,例如,您可以获取字符串的最后一个
id.length
字符,并将其与id
进行比较:
var id = "John";
var exist = "blahJohn".slice(-id.length) == id; // true
You would need to use a RegExp()
object to do that, not a literal:您需要使用
RegExp()
对象来执行此操作,而不是文字:
var id = "John",
reg = new RegExp(id+"$");
alert( reg.test("blahJon") );
That is, if you do not know the value you are testing for ahead of runtime.也就是说,如果您在运行前不知道要测试的值。 Otherwise you could do:
否则你可以这样做:
alert( /John$/.test("blahJohn") );
I like @lonesomeday 's solution, but Im fan of extending the String.prototype in these scenarios.我喜欢@lonesomeday 的解决方案,但我喜欢在这些场景中扩展 String.prototype。 Here's my adaptation of his solution
这是我对他的解决方案的改编
String.prototype.endsWith = function (needle) {
return needle === this.substr(0 - needle.length);
}
So can be checked with所以可以检查
if(myStr.endsWith("test")) // Do awesome things here.
Tasty...可口...
var id = "John";
(new RegExp(`${id}$`)).test('blahJohn'); // true
(new RegExp(`${id}$`)).test('blahJohna'); // false
`${id}$` is a JavaScript Template strings which will be compiled to 'John$'. `${id}$` 是一个 JavaScript 模板字符串,将被编译为 'John$'。
The $
after John in RegExp stands for end of string so the tested string must not have anything after id value (ie John) in order to pass the test. RegExp 中 John 之后的
$
代表字符串结尾,因此被测试的字符串必须在 id 值(即 John)之后没有任何内容才能通过测试。
new RegExp(`${id}$`) - will compile it to /John$/
(so if id shouldn't be dynamic you can use just /John$/ instead of new RegExp(`${id}$`) ) new RegExp(`${id}$`) - 将其编译为
/John$/
(所以如果 id 不应该是动态的,你可以只使用 /John$/ 而不是 new RegExp(`${id}$`) )
Try this -尝试这个 -
var reg = "/" + id + "$/";
var exists ="blahJohn".match(reg);
The nicer way to do this is to use RegExp.test
:更好的方法是使用
RegExp.test
:
(new RegExp(id + '$')).test('blahJohn'); // true
(new RegExp(id + '$')).test('blahJohnblah'); // false
Even nicer would be to build a simple function like this:更好的是构建一个像这样的简单函数:
function strEndsWith (haystack, needle) {
return needle === haystack.substr(0 - needle.length);
}
strEndsWith('blahJohn', id); // true
strEndsWith('blahJohnblah', id); // false
If you need it for replace function, consider this regExp:如果您需要它来替换功能,请考虑以下 regExp:
var eventStr = "Hello% World%";
eventStr = eventStr.replace(/[\%]$/, "").replace(/^[\%]/, ""); // replace eds with, and also start with %.
//output: eventStr = "Hello% World"; //输出:eventStr = "Hello% World";
var id = new RegExp("John");
var exists ="blahJohn".match(id);
alert(exists);
try this尝试这个
Why using RegExp?为什么使用正则表达式? Its expensive.
它的价格昂贵。
function EndsWith( givenStr, subst )
{
var ln = givenStr.length;
var idx = ln-subst.length;
return ( giventStr.subst(idx)==subst );
}
Much easier and cost-effective, is it?更容易和更具成本效益,是吗?
Just created this helper function, I find it more useful and clean than modifying the regex and recreating one everytime.刚刚创建了这个辅助函数,我发现它比修改正则表达式并每次都重新创建一个更有用和更干净。
/**
* @param {string} str
* @param {RegExp} search
* @returns {boolean}
*/
function regexEndsWith (str, search, {caseSensitive = true} = {})
{
var source = search.source
if (!source.endsWith('$')) source = source + '$'
var flags = search.flags
if (!caseSensitive && !flags.includes('i')) flags += 'i'
var reg = new RegExp(source, flags)
return reg.test(str)
}
Use it this way:以这种方式使用它:
regexEndsWith('can you Fi nD me?', /fi.*nd me?/, {caseSensitive: false})
Here is a string prototype function that utilizes regex.这是一个使用正则表达式的字符串原型函数。 You can use it to check if any string object ends with a particular string value:
您可以使用它来检查是否有任何字符串对象以特定的字符串值结尾:
Prototype function:原型功能:
String.prototype.endsWith = function (endString) {
if(this && this.length) {
result = new RegExp(endString + '$').test(this);
return result;
}
return false;
}
Example Usage:示例用法:
var s1 = "My String";
s1.endsWith("ring"); // returns true;
s1.endsWith("deez"); //returns false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.