1

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);
2
  • What are you trying to get? "i HATE you" or "[i LOVE you]"? Commented Dec 17, 2011 at 4:20
  • What is your purpose? What do you expect to see as a result? Commented Dec 17, 2011 at 4:24

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for telling me that substr is the .NET equivalent.
1

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

Comments

1

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

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.