替换空格javascript

时间:2013-05-03 08:19:16

标签: javascript jquery

我创建了一个邮政编码表格的位置。唯一的麻烦是邮政编码的结果可能包含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>

3 个答案:

答案 0 :(得分:1)

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

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

正则表达式解释:

  • [ ]括号内的字符“空格”是为了便于阅读 - 您不需要它们。
  • +重复一次或多次
  • /g不仅仅是一次,而是整个字符串中的全局

答案 1 :(得分:1)

你可以这样做:

str = str.replace(/ {2,}/g, ' ');

答案 2 :(得分:0)

str_replace ( "  " , " " , $string )