开发者

JavaScript - How to get at specific value in a string?

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


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜