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 ?

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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'];

Comments

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.

Comments

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

2 Comments

This wouldn't test correctly, since you're testing with a string, not a regex.
of course after I post this, there are 3 more answers. I should try to avoid easy questions. :(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.