Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

var id = "John"; var exists  ="blahJohn".match(/id$/); alert(exists); 
like image 898
Tony_Henrich Avatar asked Feb 14 '11 18:02

Tony_Henrich


People also ask

How to check if a string ends with something js?

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.

Does RegEx work in JavaScript?

In JavaScript, you can write RegExp patterns using simple patterns, special characters, and flags.

What is RegEx in JavaScript?

In JavaScript, a Regular Expression (RegEx) is an object that describes a sequence of characters used for defining a search pattern. For example, /^a...s$/ The above code defines a RegEx pattern. The pattern is: any five letter string starting with a and ending with s .


1 Answers

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

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 
like image 187
Christian C. Salvadó Avatar answered Sep 28 '22 23:09

Christian C. Salvadó