用连字符替换空格,但不能用逗号替换

时间:2017-07-03 06:10:51

标签: javascript node.js regex

我有一种情况,我希望将string替换为单-我能够实现此目的但问题是

var str = "Beco de    Santo António BT, Cascais , Portugal";  // input

输出

Beco-de-Santo-António-BT,-Cascais-,-Portugal  // output

但你可以看到, Cascais , Portugal我正在获得==> ,-Cascais-,-Portugal

我想要的输出:

 Beco-de-Santo-António-BT,Cascais,Portugal



var str = "Beco de    Santo António BT, Cascais , Portugal";


str2 = str.replace(/\s+/g, '-');

alert(str2);




7 个答案:

答案 0 :(得分:1)

使用word boundaries定位单词之间的空白区域。

var str = "Beco de    Santo António BT, Cascais , Portugal";


str2 = str.replace(/\b\s+\b/g, '-');

alert(str2);

答案 1 :(得分:0)

试试这个

var str = "Beco de    Santo António BT, Cascais , Portugal";

str2 = str.replace(/\s+/g, '-').replace(/,-/g, ',').replace(/-,/g, ',');

alert(str2);

答案 2 :(得分:0)



var str = "Beco de    Santo António BT, Cascais , Portugal";

str2 = str.replace(/ , /g, ', ');
str2 = str2.replace(/\s+/g, '-');
str2 = str2.replace(/,-/g, ',');

alert(str2);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

试试这个:

var str = "Beco de    Santo António BT, Cascais , Portugal";
array = str.split(",");
array = $.map(array, function(value){
   return $.trim(value).replace(/\s\s+/g, '-').replace(/ /g, '-');
});
str = array.join(",");

答案 4 :(得分:0)

这是你的工作:

function showInput(){
    var str = "Beco de    Santo António BT, Cascais , Portugal";
    var res = str.split(",");
    for (var i=0; i<res.length; i++){
        res[i] = res[i].trim();
        res[i] = res[i].replace(/\s+/g, '-');
    }
    var output = res.join();
    alert(output);
}

我正在做的是我使用逗号分割字符串并将它们放入数组然后遍历数组。 在每次迭代中,我将删除前导和尾随空格,然后替换其间的剩余空格以替换为连字符(全部完成就地),然后最后用逗号连接它们。

答案 5 :(得分:0)

var str = "Beco de    Santo António BT, Cascais , Portugal";


str2 = str.replace(/\w\s+\w/g, function(match, index){ return match.replace(/\s+/g, '-') });

alert(str2);

答案 6 :(得分:0)

首先删除,附近的额外空格,然后用-替换字符串中的空格

str.replace(/\s*,[,\s]*/g,',') // first remove spaces nearby  commas
   .replace(/\s+/g,'-'); // then replace them by -

&#13;
&#13;
var str = "Beco de    Santo António BT, Cascais , Portugal";
str2 = str.replace(/\s*,[,\s]*/g,',').replace(/\s+/g,'-');
console.log(str2);
&#13;
&#13;
&#13;