MrAdam Posted September 17, 2008 Share Posted September 17, 2008 Basically I have a string which I want to parse the numeric value from .. the string will be in this format: "Inbox [1]" (an example) .. Does anybody know a way I could return what ever's between the []s?Cheers guys!! Adam Link to comment Share on other sites More sharing options...
Ingolme Posted September 17, 2008 Share Posted September 17, 2008 I guess regular expressions would do the job, something like this: var str = "inbox[1]"; var patt1 = /inbox\[(\d*)\]/;var result = str.match(patt1)[1];alert(result); Link to comment Share on other sites More sharing options...
jeffman Posted September 17, 2008 Share Posted September 17, 2008 Looks weird, but works:str="blah[12]blah";num = str.match(/\[([0-9]+)\]/)[1];num now equals 12. Link to comment Share on other sites More sharing options...
MrAdam Posted September 17, 2008 Author Share Posted September 17, 2008 Great stuff! Works great except, when there's no match it just doesn't seem to wanna play! checked firefox error console and it says:Error: str.match(patt1) is nullHow could I run a conditional to sort of be able to say wether or not there is anything there (for example the stirng may just be: "Inbox") ??Thanks for your help pal! Adam Link to comment Share on other sites More sharing options...
jeffman Posted September 18, 2008 Share Posted September 18, 2008 How are you using str.match(patt1) ? It usually goes in a conditional, like if (result = str.match(patt1)) {do something with result}. Link to comment Share on other sites More sharing options...
MrAdam Posted September 19, 2008 Author Share Posted September 19, 2008 var patt1 = /inbox\[(\d*)\]/;if (result = document.getElementById("newMessages").innerHTML.match(patt1)[1]) { var currentCount = result;} else { var currentCount = 0;}alert(currentCount); But again, nothing happens and in the error console says patt1 is null ???I've also tried your idea Deidre's Dad, but again said = null ..Quite confused..Anybody any ideas?Cheers for the help!!Adam Link to comment Share on other sites More sharing options...
MrAdam Posted September 19, 2008 Author Share Posted September 19, 2008 Ahh realised the problem... var str = 'inbox';var matchStr = '/\[([0-9]+)\]/';if (str.match(matchStr) == null) { var currentCount = 0;} else { var currentCount = str.match(matchStr)[1];} Works perfect! Cheers guys!Adam Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.