How to check if a string \"StartsWith\" another string?

Answer

You can add this function to the String prototype:

if(typeofString.prototype.startsWith !=\'function\'){// see below for better implementation!String.prototype.startsWith =function(str){returnthis.indexOf(str)===0;};}

Then you can use it directly on string values:

\"Hello World!\".startsWith(\"He\");// truevar data =\"Hello world\";var input =\'He\';
data.startsWith(input);// true

Edit: Note that I\'m checking if the function exists before defining it, that\'s because in the future, the language might have this strings extras methods defined as built-in functions, and native implementations are always faster and preferred, see the ECMAScript Harmony String Extras proposal.

Edit: As others noted, indexOf will be inefficient for large strings, its complexity is O(N). For a constant-time solution (O(1)), you can use either, substring as @cobbal suggested, or String.prototype.slice, which behaves similarly (note that I don\'t recommend using the substr, because it\'s inconsistent between implementations (most notably on JScript) ):

if(typeofString.prototype.startsWith !=\'function\'){String.prototype.startsWith =function(str){returnthis.slice(0, str.length)== str;};}

The difference between substring and slice is basically that slice can take negative indexes, to manipulate characters from the end of the string, for example you could write the counterpart endsWith method by:

if(typeofString.prototype.endsWith !=\'function\'){String.prototype.endsWith =function(str){returnthis.slice(-str.length)== str;};}

All string Questions

Ask your interview questions on string

Write Your comment or Questions if you want the answers on string from string Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---