3

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 ?

Community
  • 1
  • 1
Lorenzo
  • 28,661
  • 47
  • 120
  • 216
  • This is a duplicate of two other questions: http://stackoverflow.com/questions/2198713/splitting-in-string-in-javascript and http://stackoverflow.com/questions/646628/javascript-startswith – Matthew Jones Nov 16 '10 at 17:10

4 Answers4

11

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.

Nick Craver
  • 610,884
  • 134
  • 1,288
  • 1,151
2

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'];
Jacob Relkin
  • 156,685
  • 31
  • 339
  • 316
1

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.

Justin Niessner
  • 236,029
  • 38
  • 403
  • 530
1

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
troynt
  • 1,880
  • 15
  • 21