Reputation: 151
I have created a location to postcode form. The only trouble is the result of the postcode may contain 2 or more spaces. I would like to make sure that there isn't more than one space. In other words >1 space change to 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 is denied!");
} else if( err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function gotpostcode(result)
{
var postcode = result.postcode;
$("#postcodegoeshere").val(postcode);
}
function getLocation(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
navigator.geolocation.getCurrentPosition(showLocation,
errorHandler,
options);
} else {
alert("Sorry, browser does 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>
Upvotes: 0
Views: 183
Reputation: 39522
Use regex and replace /[ ]+/g
with a space.
var str = "this has a lot of whitespaces";
var str = str.replace(/[ ]+/g, " ");
console.log(str);
//this has a lot of whitespaces
Regex explanation:
[ ]
the character "space" enclosed in brackets for readability - you don't need them.+
repeated 1 or more times/g
not just once, but globally in the whole stringUpvotes: 1