views:

145

answers:

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

Going after the value in a span (id=customerAddress) and I'd like to reduce all sections of whitespace to a single whitespace. The /\s+/ whould work except this app gets some character 160's between street address and state/zip What is a better way to write this? this does not currently work.

UPDATE: I have figured out that

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

clears the 160s and the spaces. But how would I write a regex to just go after the 160s?

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

didn't even work.

Note: I'm testing in Firefox / Firebug

A: 

Sorry if I'm being obvious (or wrong), but doesn't .text() when called w/o parameters just RETURNS the text? I mean, I don't know if you included the full code or just an excerpt, but to really replace the span you should do it like:

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

Other than that, the regex for collapsing the spaces seems OK, I'm just not sure about the syntax of your non-printable char there.

Rafael Almeida
http://indopedia.org/Unicode_characters_160-191.html I think it is sometimes written as   which I think sometimes is a valid replacement for   (but I know that is character 32)
tyndall
The problem is the replace(/\xA0/,"") has no effect. I'm sure the characters are 160. checked them with Excel =CODE( )
tyndall
$('.customerAddress').text().charCodeAt(24) also == 160
tyndall
this doesn't work $('.customerAddress').text().replace(String.fromCharCode(160)," "); weird
tyndall
What exactly is "doesn't work"? Did you try alert()'ing this expression or you're hoping it would modify the text in place? - Just to clarify.
Rafael Almeida
+2  A: 

\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]

But you should add the g modifier to replace globally:

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

Otherwise only the first match will be replaced.

Gumbo
how were you able to find what \s contains? would love to know that trick? +1
tyndall
@tyndall: I already knew that and just looked up the actual definition.
Gumbo
+1  A: 

Regarding just replacing char 160, you forgot to make a global regex, so you are only replacing the first match. Try this:

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

Or even simpler, use your Hex example in your question with the global flag

$('.customerAddress').text().replace(/\xA0/g," ");
Mark Porter
I hate it when I miss something like this +1
tyndall