3

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

7 Answers 7

9

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

Comments

3

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.

1 Comment

In the question, he asked for everything from the "S" on, cutting out the " - " part. Of course, the code agrees with what you have.
0

try

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

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

2 Comments

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.
An alternative to using the broken split-maximum feature would be, say: “x.split(' - ').slice(1).join(' - ')”, to put back any additional ‘ - ’ strings.
0
var y = x.substring(0, x.lastIndexOf(' - ') + 3)

Comments

0

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.

2 Comments

doesn't slice allow -1 as equivalent to x.length-1?
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.
0
x.substring(x.lastIndexOf(" - "),x.length-1); //corrected

1 Comment

This will actually cause a runtime error because x.length is past the end of the string. I think you meant x.length - 1.
0
var y = x.slice(x.lastIndexOf("-")+2);

Usually, we don't have space so we write +1 but in your case +2 works fine.

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.