Skip to content Skip to sidebar Skip to footer

JavaScript/jQuery Removing Character 160 From A Node's Text() Value - Regex

$('#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 sin

Solution 1:

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," ");

Solution 2:

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


Solution 3:

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.


Post a Comment for "JavaScript/jQuery Removing Character 160 From A Node's Text() Value - Regex"