Alex Guerin
Alex Guerin

Reputation: 2386

JavaScript: getting part of string using substring

I have a variable in JavaScript:

var text = "i HATE you[i LOVE you]"

The code below originated from VB. I've checked it against W3Schools but I cannot see why it won't work.

var test = text.Substring(text.IndexOf("[") + 1, text.IndexOf("]") - text.IndexOf("[") - 1);
document.write(test);

Upvotes: 1

Views: 278

Answers (4)

勿绮语
勿绮语

Reputation: 9320

The second parameter is the "end index", not the "length". Or you can use regex.

Upvotes: 1

Filip Roséen
Filip Roséen

Reputation: 63797

Reasons why your current solution fails:

  • javascript is case-sensitive you trying to call String.IndexOf won't work, instead you have to write it as indexOf.

  • same reason as previous list entry, SubString should be written as substring, in the method you are using it seems like you are looking for substr (because of your arguments).

Alternative solutions

There are several ways to simplify your method of getting the text inbetween [and ], I wrote three examples below.

 text.substring (text.indexOf ('[')+1, text.lastIndexOf (']'));

 text.substr (n=text.indexOf('[')+1, text.indexOf (']')-n);

 text.split (/\[|\]/)[1];

 text.match (/\[(.*?)\]/)[1];

Upvotes: 1

Guffa
Guffa

Reputation: 700172

Javascript is case sensetive, so it doesn't have any Substring or IndexOf methods, it has substring and indexOf methods. However, the .NET method SubString corresponds to the Javascript method substr:

var test = text.substr(text.indexOf("[") + 1, text.indexOf("]") - text.indexOf("[") - 1);

Upvotes: 3

Jimmy
Jimmy

Reputation: 37081

Not sure what output you're expecting, but the obvious issue is that your casing is wrong. Method names are case sensitive. You'd need this instead:

text.substring(text.indexOf("[") + 1, text.indexOf("]") - text.indexOf("[") - 1);

Upvotes: 0

Related Questions