views:

651

answers:

6

I have a string "2500 - SomeValue". How can I remove everything before the 'S' in 'SomeValue'?

var x = "2500 - SomeValue";
var y = x.substring(x.lastIndexOf(" - "),
// this is where I'm stuck, I need the rest of the string starting from here.

Thanks for any help.

~ck

A: 
x.substring(x.lastIndexOf(" - "),x.length-1); //corrected
andreas
This will actually cause a runtime error because `x.length` is past the end of the string. I think you meant `x.length - 1`.
Joel Potter
Correct - tried for a fast answer but failed
andreas
+3  A: 

That's just:

var y = x.substring(x.lastIndexOf(" - ") + 3);

When you omit the second parameter, it just gives you everything to the end of the string.

EDIT: Since you wanted everything from after the " - " I've added 3 to the starting point in order to skip those characters.

VoteyDisciple
In the question, he asked for everything from the "S" on, cutting out the " - " part. Of course, the code agrees with what you have.
Matthew Crumley
Good point. Edited accordingly.
VoteyDisciple
A: 

try

var y = x.split(" ",2);

then you'll have an array of substrings. The third one y[2] will be what you need.

Sorantis
When you use ‘split(' ', 2)’, you will end up with an array of maximum 2 elements, and if there are 2 or more spaces, the rest will be thrown away... so this doesn't work for the above example. You're trying to use ‘String.split(..., maximum)’ as if it worked sensibly like in Python; unfortunately JavaScript is not sensible.
bobince
An alternative to using the broken split-maximum feature would be, say: “x.split(' - ').slice(1).join(' - ')”, to put back any additional ‘ - ’ strings.
bobince
A: 
var y = x.substring(0, x.lastIndexOf(' - ') + 3)
Jimmy
A: 

var y = x.slice(x.lastIndexOf(" - "), x.length - 1);

This will return the value as a string no matter that value is or how long it is and it has nothing to do with arrays.

doesn't slice allow -1 as equivalent to x.length-1?
Jimmy
slice requires a terminal value. If the string is of variable length then that is how you find its length for static measurement. A value of -1 would not work, because as an index the value -1 returns undefined. In this case that would likely throw an error.
+4  A: 

Add 3 (the length of " - ") to the last index and leave off the second parameter. The default when you pass one parameter to substring is the go to the end of the string

var y = x.substring(x.lastIndexOf(" - ") + 3);
Matthew Crumley