how would i write the equivalent of c# startswith in javascript?
var data = 'hello world'; var input = 'he';
//data.startsWith(input) == true
how would i write the equivalent of c# startswith in javascript?
var data = 'hello world'; var input = 'he';
//data.startsWith(input) == true
You can add this function to the String prototype:
String.prototype.startsWith = function(str){
return (this.indexOf(str) === 0);
}
"Hello World!".startsWith("He"); // true
var data = "Hello world";
var input = 'He';
data.startsWith(input); // true
var str = 'he';
var data = 'hello world';
String.prototype.startsWith = function(s) { if( this.indexOf(s) == 0 ) return true; return false; }
if( data.startsWith(str) ) return true;
Here is a minor improvement to CMS's solution:
if(!String.prototype.startsWith){
String.prototype.startsWith = function (str) {
return !this.indexOf(str);
}
}
"Hello World!".startsWith("He"); // true
var data = "Hello world";
var input = 'He';
data.startsWith(input); // true
Checking whether the function already exists in case a future browser implements it in native code or if it is implemented by another library. For example, the Prototype Library implements this function already.
Using ! is slightly faster and more concise than " === 0" though not as readable.