Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (7k points)

How can I check if a string starts with another string in JavaScript?

1 Answer

0 votes
by (13.1k points)

You can use String.prototype.startsWith() method, but it is not supported in all browsers. You will need to use a shim/ polyfill to add it on browsers that don’t support it.

If you want a shim that works then use either Matthias Bynens’s String.prototype.startsWith or es-6 shim, which shims as much of the ES6 as of the ES6 spec as possible, including String.prototype.startsWith. Once you have shimmed the method, you can use it like this:

 console.log("Hello World!".startsWith("He")); // true    

var haystack = "Hello world";

var prefix = 'orl';

console.log(haystack.startsWith(prefix)); // false

Want to be a full stack developer? Check out the full stack developer course from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...