regular expressions basics - match all numbers in string

notes and quirk solutions found over time
Post Reply
darknkreepy3#
Site Admin
Posts: 254
Joined: Tue Oct 27, 2009 9:33 pm

regular expressions basics - match all numbers in string

Post by darknkreepy3# »

Here is a very simple basic regular expression test to teach you how to match number sequences in a string.

Code: Select all

<html>
	<body>
		Original String 'origStr'<br />
		<textarea id="origStr" cols="80" rows="2"></textarea><br />
		origStr.match(/(\d+)/g)<br />
		<textarea id="debug" cols="80" rows="1"></textarea>
	</body>
</html>
<script language="javascript" type="text/javascript">
var debugDiv=document.getElementById('debug');
var origStrDiv=document.getElementById('origStr');
/*
within /  /
d+ means match one or more numbers in a row  find all numbers by finding a number character 2..7..4 
after /  / g means find all occurences inside of the string, without the g at the end means find only the first ocurence (274)
*/
var expr1=/(\d+)/g;
var origStr="Welcome to Facebook, you have 274 friends currently. 2 of your friends are happy. There are [80] new messages.";
var newStrArr=origStr.match(expr1);
debugDiv.innerHTML=newStrArr;
origStrDiv.innerHTML=origStr;
</script>
Post Reply