jimfog Posted June 16, 2011 Share Posted June 16, 2011 This might look like a silly question but it is in my effort comprehend javascript.Suppose we have a body of text(in a webpage)IF in this body there is a number(5 for example) would this be treated by javascript as a string or as a number?What i want to say is, do special occasions must exist in order for a number in a text be treated as "number" from javascript?I hope i did not confuse you. Link to comment Share on other sites More sharing options...
Ingolme Posted June 16, 2011 Share Posted June 16, 2011 All the content on a website is treated as a string, but casting to a number is very simple. Link to comment Share on other sites More sharing options...
jeffman Posted June 16, 2011 Share Posted June 16, 2011 If you can isolate the number from the rest of the text content, it can be treated as a number. A regular expression would be ideal for that, probably. For example: var s = "dh4dkhjd567kjhkjh890dlgd";var re = /\d+/g;var matches = s.match(re);alert(matches[0]); // "4"alert(matches[1]); // "567"alert(matches[2]); // "890" The re can get more precise if you need it to. Link to comment Share on other sites More sharing options...
jeffman Posted June 16, 2011 Share Posted June 16, 2011 You have to be careful with implicit casting, though, especially when using the overloaded + operator "5" * 5 // 25"5" + 5 // "55"Number("5") + 5 // 10 Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.