jquery - Replace spaces javascript -
i have created location postcode form. trouble result of postcode may contain 2 or more spaces. make sure there isn't more 1 space. in other words >1 space change 1 space.
<!doctype html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script> <script type="text/javascript"> function showlocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; $.getjson('http://www.uk-postcodes.com/latlng/' + position.coords.latitude + ',' + position.coords.longitude + '.json?callback=?', null, gotpostcode); } function errorhandler(err) { if(err.code == 1) { alert("error: access denied!"); } else if( err.code == 2) { alert("error: position unavailable!"); } } function gotpostcode(result) { var postcode = result.postcode; $("#postcodegoeshere").val(postcode); } function getlocation(){ if(navigator.geolocation){ // timeout @ 60000 milliseconds (60 seconds) var options = {timeout:60000}; navigator.geolocation.getcurrentposition(showlocation, errorhandler, options); } else { alert("sorry, browser not support geolocation!"); } } </script> </head> <html> <body> <form> <input type="button" onclick="getlocation();" value="get location"/> </form> <div> <input id='postcodegoeshere' name='xxx' type='text' value='' /> </div> </body> </html>
use regex , replace /[ ]+/g space.
var str = "this has lot of whitespaces"; var str = str.replace(/[ ]+/g, " "); console.log(str); //this has lot of whitespaces regex explanation:
[ ]character "space" enclosed in brackets readability - don't need them.+repeated 1 or more times/gnot once, globally in whole string
Comments
Post a Comment