1

I have a string from which I am trying to get a specif value. The value is buried in the middle of the string. For example, the string looks like this:

 Content1Save

The value I want to extract is "1";

Currently, I use the built-in substring function to get to remove the left part of the string, like this:

MyString = "Content1Save";
Position = MyString;
Position = Position.substring(7);
alert(Position); // alerts "1Save"

I need to get rid of the "Save" part and be left with the 1;

How do I do that?

+++++++++++++++++++++++++++++++++++++++++ ANSWER

Position = Position.substr(7, 1);

QUESTION

What's the difference between these two?

Position = Position.substr(7, 1);
Position = Position.substring(7, 1);
4

4 Answers 4

4

You can use the substr[MDN] method. The following example gets the 1 character long substring starting at index 7.

Position = Position.substr(7, 1);

Or, you can use a regex.

Position = /\d+/.exec(Position)[0];
Sign up to request clarification or add additional context in comments.

Comments

3

I would suggest looking into regex, and groups.

Regex is built essentially exactly for this purpose and is built in to javascript. Regex for something like Content1Save would look like this:

rg = /^[A-Za-z]*([0-9]+)[A-Za-z]*$/

Then you can extract the group using:

match = rg.exec('Content1Save');
alert(match[1]);

More on regex can be found here: http://en.wikipedia.org/wiki/Regular_expression

Comments

1

It highly depends on the rules you have for that middle part. If it's just a character, you can use Position = Position.substring(0, 1). If you're trying to get the number, as long as you have removed the letters before it, you can use parseInt.

alert(parseInt("123abc")); //123
alert(parseInt("foo123bar")); //NaN

Comments

1

If you're actually trying to search, you'll more often than not need to use something called Regular Expressions. They're the best search syntax JavaScript avails.

var matches = Position.match(/\d+/)
alert(matches[0])

Otherwise you can use a series of substr's, but that implies you know what is in the string to begin with:

MyString.substr(MyString.indexOf(1), 1);

But that is a tad annoying.

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.