How do I spit a string and test for the start of a string in javascript/jquery? [duplicate]
Possible Duplicates:
Splitting in string in JavaScript javascript startswith
Hello I have a string in javascript and I need to manipulate it. The string format is as follow
xxx_yyy
I need to:
- reproduce the behaviour of the
string.StartsWith("xxx_")
in c# - split the string in two strings as I would do with
string.Split("_")
in c#
any help ?
There's no jQuery needed here, just plain JavaScript has all you need with .indexOf()
and .split()
, for example:
var str = "xxx_yyy";
var startsWith = str.indexOf("xxx_") === 0;
var stringArray = str.split("_");
You can test it out here.
Here you go:
String.prototype.startsWith = function(pattern) {
return this.indexOf(pattern) === 0;
};
split
is already defined as a String
method, and you can now use your newly created startsWith
method like this:
var startsWithXXX = string.startsWith('xxx_'); //true
var array = string.split('_'); //['xxx', 'yyy'];
You can easily emulate StartsWith() by using JavaScript's string.indexOf()
:
var startsWith = function(string, pattern){
return string.indexOf(pattern) == 0;
}
And you can simply use JavaScript's string.split()
method to split.
JavaScript has split built-in.
'xxx_yyy'.split('_'); //produces ['xxx','yyy']
String.prototype.startsWith = function( str ) {
return this.indexOf(str) == 0;
}
'xxx_yyy'.startsWith('xxx'); //produces true
精彩评论