Check if string ends with any of multiple characters

for some reason the accepted answer's function was giving me problems so I wrote this function that works for me:

//check if string ends with any of array suffixes
function endsWithAny(suffixes, string) {
    for (let suffix of suffixes) {
        if(string.endsWith(suffix))
            return true;
    }
    return false;
}

so then your function is

function myFunction() {
    var str = "Hello?";
    var n = endsWithAny([".", "!", "?"], str);
    document.getElementById("demo").innerHTML = n;
}

You can use indexOf in combination with slice:

function myFunction() {
    var str = "Hello?";
    var n = '.!?'.indexOf(str.slice(-1)) >= 0;
    document.getElementById("demo").innerHTML = n;
}
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

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

Tags:

Javascript