|
-
March 7th, 2010, 12:25 PM
#1
Best way to obtain value from string?
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!
-
March 8th, 2010, 12:34 AM
#2
Re: Best way to obtain value from string?
Last edited by rohshall; March 8th, 2010 at 12:54 AM.
Reason: split function
-
March 8th, 2010, 08:19 AM
#3
Re: Best way to obtain value from string?
Regular expressions would indeed be a very good way to do it. Try this:
Code:
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.
Last edited by PeejAvery; March 8th, 2010 at 10:18 AM.
Reason: Added code tags.
-
March 9th, 2010, 01:00 PM
#4
Re: Best way to obtain value from string?
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
-
March 9th, 2010, 02:54 PM
#5
Re: Best way to obtain value from string?
So grab the whole array with pattern matching.
Code:
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
If the post was helpful...Rate it! Remember to use [code] or [php] tags.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|