views:

10540

answers:

4

how would i write the equivalent of c# startswith in javascript?

var data = 'hello world'; var input = 'he';

//data.startsWith(input) == true

+20  A: 
data.substr(0, input.length) === input
cobbal
This is most efficient
Silas Hansen
+39  A: 

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
CMS
If the string is very long, this could be quite inefficient.
Amir
There is an efficient solution by @cobbal which only check the first bytes instead of the entire string.
Shay Erlichmen
+1  A: 

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;

Abhishek
+7  A: 

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.