0

我已经创建了一个邮政编码表格的位置。唯一的麻烦是邮政编码的结果可能包含 2 个或更多空格。我想确保不超过一个空格。换句话说,>1 个空格变为 1 个空格。

<!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>
4

3 回答 3

1

使用正则表达式并/[ ]+/g用空格替换。

var str = "this     has    a lot of     whitespaces";
var str = str.replace(/[ ]+/g, " ");
console.log(str); 
//this has a lot of whitespaces

正则表达式解释:

  • [ ]为了便于阅读,括号中的字符“空格” - 您不需要它们。
  • +重复 1 次或多次
  • /g不只是一次,而是在整个字符串中全局
于 2013-05-03T08:22:16.690 回答
1

你可以这样做:

str = str.replace(/ {2,}/g, ' ');
于 2013-05-03T08:24:35.380 回答
0
str_replace ( "  " , " " , $string )
于 2013-05-03T08:33:44.773 回答