Click to See Complete Forum and Search --> : Best way to obtain value from string?


Lucky75
March 7th, 2010, 11:25 AM
Hi, I'm looking to do some parsing of a string to obtain a value, but I'm unsure of the best way to get it.

For example, if my string is "You have XXX days remaining until the end of the world", how would I get the value of XXX? It will always be a number, but of unknown number of digits.

I was almost thinking of splitting based on the spaces, but I don't have confidence that the server will return a message with a consistent number of spaces every time.

Is there a quick way to do it with regular expressions or something?

Thanks!

rohshall
March 7th, 2010, 11:34 PM
You answered your own question:

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

However, there is an easier way to do this:
http://www.w3schools.com/jsref/jsref_split.asp

the_cat
March 8th, 2010, 07:19 AM
Regular expressions would indeed be a very good way to do it. Try this:

var pat=/\d+\s/g;
var txt="You have 999 days remaining until the end of the world";
var result=parseInt(pat.exec(txt));
if (isNaN(result)) {
document.write("The world is over");
}
else {
document.write("Days remaining: " + result);
}

The pattern it's looking for is one or more numbers and a space. If the "result" is not a number (isNaN) then no number was found and some text is displayed. Otherwise the number of days remaining is displayed.

Lucky75
March 9th, 2010, 12:00 PM
Hmm, thanks for the responses. I think regular expressions would be cleaner, but I forgot to mention that the string would actually have two different numbers.

So if it was "You have tried 5 times, and there are 999 days remaining until the end of the world."

I couldn't use the standard regular expression anymore looking for just a number, could I? Is it possible to always select the second series of integers?

Thanks:)

PeejAvery
March 9th, 2010, 01:54 PM
So grab the whole array with pattern matching.

var pattern = /\d+/g;
var txt = "You have 999 days remaining until the 5 end of the world";
var result = txt.match(pattern); // returns array of numerical matches