In JavaScript possiamo verificare se una stringa inizia con un determinato carattere usando un metodo specifico.
startsWith() restituisce un valore booleano che indica il risultato della verifica:
'use strict';
const str = 'Test';
str.startsWith('T'); // true
startsWith() è stato introdotto in ECMAScript 6. Se si devono supportare browser obsoleti, si può usare il seguente approccio:
'use strict';
function startsWith(str, char) {
if(typeof String.prototype.startsWith === 'function') {
return str.startsWith(char);
}
return str[0] === char;
}