How can I check if a string ends with a particular character in JavaScript?
Example: I have a string
var str = \"mystring#\";
I wa
/#$/.test(str)
will work on all browsers, doesn't require monkey patching String
, and doesn't require scanning the entire string as lastIndexOf
does when there is no match.
If you want to match a constant string that might contain regular expression special characters, such as '$'
, then you can use the following:
function makeSuffixRegExp(suffix, caseInsensitive) {
return new RegExp(
String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
caseInsensitive ? "i" : "");
}
and then you can use it like this
makeSuffixRegExp("a[complicated]*suffix*").test(str)