Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string ends with any of multiple characters

Tags:

javascript

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>
like image 771
Taylor Avatar asked Jul 13 '17 00:07

Taylor


People also ask

How do you know if a string ends with certain characters?

The endsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.

How do you check if a string ends with a character in Java?

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

How do you check if a string ends with a substring in Java?

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.


1 Answers

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);
like image 96
Ry- Avatar answered Sep 28 '22 16:09

Ry-