Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Friday, June 1, 2012
Javascript StartsWith
How would I write the equivalent of C#'s String.StartsWith in Javascript?
You can add this function to the String prototype:
if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str){ return this.indexOf(str) == 0; }; }
Then you can use it directly on string values:
"Hello World!".startsWith("He"); // true
var 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 (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str){ return this.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 (typeof String.prototype.endsWith != 'function') { String.prototype.endsWith = function (str){ return this.slice(-str.length) == str; }; }
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.
You can add this function to the String prototype:
ReplyDeleteif (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.indexOf(str) == 0;
};
}
Then you can use it directly on string values:
"Hello World!".startsWith("He"); // true
var 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 (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.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 (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function (str){
return this.slice(-str.length) == str;
};
}
data.substring(0, input.length) === input
ReplyDeleteHere's another alternative:
ReplyDeletedata.lastIndexOf(str, 0) === 0
It doesn't check the entire string.
It doesn't create a new temporary string and then immediately discard it.
Here is a minor improvement to CMS's solution:
ReplyDeleteif(!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.
Here's a related JS Perf. Looks like lastIndexOf is a good cross-browser choice.
ReplyDeletehttp://jsperf.com/js-startswith/6
Without the use of a helper function:
ReplyDelete(/^He/).test('Hello world')
Also check out underscore.string.js. It comes with a bunch of useful string testing and manipulation methods.
ReplyDeletevar str = 'he';
ReplyDeletevar data = 'hello world';
String.prototype.startsWith = function(s)
{
if( this.indexOf(s) == 0 ) return true;
return false;
}
if( data.startsWith(str) ) return true;
var str = 'hol';
ReplyDeletevar data = 'hola mundo';
if (data.length >= str.lenght && data.substring(0, str.length) == str)
return true;
else
return false;