正则表达式字符串以在 Javascript 中不起作用结束 [英] Regex string ends with not working in Javascript

查看:28
本文介绍了正则表达式字符串以在 Javascript 中不起作用结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对正则表达式不是很熟悉.我试图测试一个字符串是否以另一个字符串结尾.当我期望为 true 时,下面的代码返回 null.代码有什么问题?

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. What's wrong with the code?

var id = "John";
var exists  ="blahJohn".match(/id$/);
alert(exists);

推荐答案

好吧,使用这种方法,您需要使用 RegExp 构造函数,使用 id 变量构建正则表达式:

Well, with this approach, you would need to use the RegExp constructor, to build a regular expression using your id variable:

var id = "John";
var exists = new RegExp(id+"$").test("blahJohn");
alert(exists);

但是有很多方法可以实现,例如,您可以取字符串的最后一个 id.length 字符,并将其与 id 进行比较:

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:

var id = "John";
var exist = "blahJohn".slice(-id.length) == id; // true

这篇关于正则表达式字符串以在 Javascript 中不起作用结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆