正则表达式字符串以在 Javascript 中不起作用而结束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4996033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:08:24  来源:igfitidea点击:

Regex string ends with not working in Javascript

javascriptregex

提问by Tony_Henrich

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?

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

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

回答by CMS

Well, with this approach, you would need to use the RegExpconstructor, to build a regular expression using your idvariable:

好吧,使用这种方法,您需要使用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.lengthcharacters of the string, and compare it with id:

但是有很多方法可以实现这一点,例如,您可以获取id.length字符串的最后一个字符,并将其与id

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

回答by James Sumners

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") );

回答by Sachin Shanbhag

Try this -

尝试这个 -

var reg = "/" + id + "$/";
var exists  ="blahJohn".match(reg);

回答by lonesomeday

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

回答by stephen mc

I like @lonesomeday 's solution, but Im fan of extending the String.prototype in these scenarios. Here's my adaptation of his solution

我喜欢 @lonesomeday 的解决方案,但我喜欢在这些场景中扩展 String.prototype。这是我对他的解决方案的改编

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...

可口...

回答by Alexander Sobolev

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?

更容易和划算,是吗?

回答by Stewie Griffin

var id = new RegExp("John");
var exists  ="blahJohn".match(id);
alert(exists);

try this

尝试这个

回答by Dudi

If you need it for replace function, consider this regExp:

如果您需要它来替换功能,请考虑这个正则表达式:

var eventStr = "Hello% World%";

eventStr = eventStr.replace(/[\%]$/, "").replace(/^[\%]/, ""); // replace eds with, and also start with %.

//output: eventStr = "Hello% World";

//输出: eventStr = "Hello% World";

回答by Alexander

var id = "John";

(new RegExp(`${id}$`)).test('blahJohn');  // true
(new RegExp(`${id}$`)).test('blahJohna'); // false

`${id}$` is a JavaScript Template stringswhich will be compiled to 'John$'.

`${id}$` 是一个 JavaScript模板字符串,它将被编译为 'John$'。

The $after John in RegExp stands for end of stringso the tested string must not have anything after id value (i.e. John) in order to pass the test.

$RegExp 中的after 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}$`) )

回答by Ben Ronan

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;