How would I check to see if a string ends in any one of multiple characters? Currently this code returns false, even though the string ends in a question mark.The properly working code would return true if the string ends in either a period, exclamation mark, or question mark, and return false if its last character is anything else.
Obviously I could check these conditions independently but suppose I had a very long list, surely there is a better way?
function myFunction() {
var str = "Hello?";
var n = str.endsWith(".", "!", "?");
document.getElementById("demo").innerHTML = n;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
The endsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.
The endsWith() method checks whether a string ends with the specified character(s). Tip: Use the startsWith() method to check whether a string starts with the specified character(s).
We can use the endsWith() method of String class to check whether a string ends with a specific string or not, it returns a boolean value true or false.
endsWith
just doesn’t take multiple strings to test. You could define an array of them and check each value with endsWith
:
function endsWithAny(suffixes, string) {
return suffixes.some(function (suffix) {
return string.endsWith(suffix);
});
}
function myFunction() {
var str = "Hello?";
var n = endsWithAny([".", "!", "?"], str);
document.getElementById("demo").innerHTML = n;
}
Or use a regular expression for a one-off:
var n = /[.!?]$/.test(str);
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