Tuesday 15 March 2011

regex - javascript splitting a var that is numbers and letters -



regex - javascript splitting a var that is numbers and letters -

i'd prefer not utilize regex, if needed, it.

i have code , want take user's input , check create sure isbn 10. in other words must 10 digit number or 9 digit number x @ end (the x represents number 10). purposes, i'd turn users input array of each digit. if there x i'd alter 10. having problem doing this! have seen other questions similar , utilize regex. said, i'd prefer not utilize regex, if need be...

<h1>problem #3:</h1> <form name= "form"> <input id= "input" name= "isbn" type="number" placeholder="enter isbn-10" min="0" /> <input id= "button" type="button" name="validate" value="validate" /> </form> <div id="validisbn"> valid isbn </div> <div id="invalidisbn"> invalid isbn </div> <script src="js/jquery-2.0.3.min.js"></script> <script> $( document ).ready(function() { alert("welcome isbn validator!"); //add event listener validate button here //look @ toggling css display property based on result $("#button").click(function(){ checker(document.form.isbn.value); }); }); var checker = function(isbn){ isbn = isbn.tostring().split(''); if (isbn[9] == 'x'|| isbn[9] == 'x') { isbn[9] = 10; } if (isbn.length !== 10) { alert("invalid isbn!" + isbn.length); } else{ var sum = 0; (var x=10; x>0; x--){ sum += x*isbn[10-x]; } alert("final!!" + sum%11); } }

input: 0375726721 output: final!!0 :works

input:067978330x expected output: final!!0 actual output: invalid isbn!0 :does not work!

var isbn = '074759582x'; if (!/^\d{9}(\d|x)$/i.test(isbn)) // validation regexp alert('invalid isbn'); else { var arr = isbn.split(''); arr[9] = arr[9].tolowercase() == 'x' ? 10 : arr[9]; // replacement of x 10 // below summation, performed in way. var total = arr.map(function(el, index, arr) { homecoming (index + 1) * arr[10 - index - 1]; }).reduce(function(a, b) {return + b;}); alert(total % 11); }

done

javascript regex

No comments:

Post a Comment