mmm
mmm

Reputation: 2297

substr giving wrong value - javascript

For some reason, when I do the following:

var input = 'focus name (tag1 tag2 OTHER,STUFF) focus 2 (MORE)';
var openParen = input.indexOf('(');
var closeParen = input.indexOf(')');
var parenStr = input.substr(openParen + 1, closeParen - 1);

I expect parenStr to equal "tag1 tag2 OTHER,STUFF".

Instead, I'm getting it as "tag1 tag2 OTHER,STUFF) focus 2 ". Can anyone explain this to me?I feel like I'm going crazy haha, I've tried manually entering:

input.substr(openParen + 1, 32)

but it gives the exact same result. I've used .substr() tons of times before and never run into this kind of error before, I must be missing something.

Upvotes: 1

Views: 507

Answers (2)

Cheery
Cheery

Reputation: 16214

var input = 'focus name (tag1 tag2 OTHER,STUFF) focus 2 (MORE)';
var openParen = input.indexOf('(');
var closeParen = input.indexOf(')');
alert(input.substr(openParen + 1, closeParen - openParen - 1));

Upvotes: -2

Afforess
Afforess

Reputation: 934

You meant to use substring:

input.substring(openParen + 1, closeParen);

substring takes a start and end index as parameters. substr takes a start index and length parameter, which is not what you intended.

Upvotes: 6

Related Questions