Shasha Girl Shasha Girl - 26 days ago 6
Javascript Question

String.startwith Vs regex

There is a dynamic string and I want to validate whether it starts with 'image'. For that I'm using below code snippet.

var isValidImage = inputType.startsWith('image');


Is this the recommended way or should I use regX here? What is the best option?

Answer

If you care about case sensitivity then you could use a regex

var isValidImage = /^image/i.test(inputType);

If not then you can just use startsWith, but keep in mind browser compatibility. You might need a Polyfill.

It is simpler to just use the regex which is compatible everywhere.

Comments