JavaScript / jQuery从节点的text()值中删除字符160 - Regex

时间:2010-04-15 16:04:34

标签: javascript jquery regex

$('#customerAddress').text().replace(/\xA0/,"").replace(/\s+/," ");

追踪跨度中的值(id = customerAddress),我想将空白的所有部分缩减为单个空格。 / \ s + /可以工作,除了这个应用程序在街道地址和州/邮政编码之间得到一些字符160 写这个更好的方法是什么?这目前无效。

更新: 我已经想通了

$('.customerAddress').text().replace(/\s+/g," ");

清除160s和空格。 但是,如何在60年代之后编写正则表达式呢?

$('.customerAddress').text().replace(String.fromCharCode(160)," ");

甚至没有工作。

注意:我正在使用Firefox / Firebug进行测试

3 个答案:

答案 0 :(得分:11)

关于刚刚替换char 160,你忘了制作全局正则表达式,所以你只是替换了第一场比赛。试试这个:

$('.customerAddress').text()
    .replace(new RegExp(String.fromCharCode(160),"g")," ");

或者甚至更简单,使用全局标志

在问题中使用Hex示例
$('.customerAddress').text().replace(/\xA0/g," ");

答案 1 :(得分:9)

\s does already contain the character U+00A0

[\t\n\v\f\r \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]

但是你应该添加 g 修饰符来全局替换:

$('#customerAddress').text().replace(/\s+/g, " ")

否则只会替换第一场比赛。

答案 2 :(得分:0)

很抱歉,如果我显而易见(或错误),但是在调用w / o参数时没有.text()只返回文本?我的意思是,我不知道你是否包括完整的代码或只是摘录,但要真正取代你应该这样做的范围:

var t = $('#customerAddress').text().replace(/\xA0/,"").replace(/\s+/," ");
$('#customerAddress').text(t);

除此之外,用于折叠空格的正则表达式似乎没问题,我只是不确定那里的不可打印字符的语法。