0

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>
Darkzaelus
  • 2,059
  • 1
  • 15
  • 31
Steve
  • 151
  • 2
  • 12

3 Answers3

1

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 string
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
1

You can do this:

str = str.replace(/ {2,}/g, ' ');
palaѕн
  • 72,112
  • 17
  • 116
  • 136
0
str_replace ( "  " , " " , $string )
Er.KT
  • 2,852
  • 1
  • 36
  • 70
  • 1. This is PHP - 2. This would turn `my string[SPACE][SPACE][SPACE][SPACE]hey` into `my string[SPACE][SPACE]he`, so it doesn't work as well as `preg_replace("/[ ]+/", " ", $string)` would. – h2ooooooo May 03 '13 at 09:04