Reputation: 19
i am not sure as to why this code is not working, on the website where i found the code it say it should print any letter between capital a to z. i tried the same thing with a number, to print numbers between 0-9 but it does not work.
<!DOCTYPE html>
<html>
<body>
<script>
var string = "THIS IS AN EXAMPLE";
var str = /[A-Z]/;
document.write(string.match(str));
</script>
</body>
</html>
Upvotes: 0
Views: 85
Reputation: 2105
EDIT:
updated after clarified question
<script>
var string = "1 2 3 4 8 9 11 15 18 293";
var str = /[0-9]*/g;
var arr = string.match(str);
var length = arr.length;
for (var i = 0; i < length; i++) {
if ( parseInt(arr[i]) <= 9 && parseInt(arr[i]) >= 1){
document.write(arr[i] + " ");
}
}
</script>
what you are telling javascript to do is only print the first character in the array of results matching your regex. you also have not accounted for the "space" character in your regular expression
to the best of my understanding this is what you are trying to accomplish - but if this is incorrect please clarify what results you are trying to achieve.
<script>
var string = "THIS IS AN EXAMPLE";
var str = /[A-Z ]*/;
document.write(string.match(str));
</script>
note how ive used /[A-Z ]*/
including the space character in the matching set as well as an asterisk to denote matching any number of these characters. if you are attempting to only match the first word and stop at a space simply remove it.
in either case
in case you decide you would like to take a gander at the 'manual'
Upvotes: 3