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);
The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.
In JavaScript, you can write RegExp patterns using simple patterns, special characters, and flags.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With