Shasha Girl Shasha Girl - 1 year ago 137
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download