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
  • 29,081
  • 49
  • 125
  • 222
  • 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
  • 623,446
  • 136
  • 1,297
  • 1,155
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
  • 161,348
  • 33
  • 346
  • 320
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
  • 242,243
  • 40
  • 408
  • 536
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,900
  • 15
  • 21