Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a non-breakable white space in IE7 and IE8 in Javascript

I want to replace white spaces in any relatively modern browser (thus for IE, version >= 7).

Thus given the string "Hello world!" we would do:

<script type="text/javascript">
document.write("Result: '" + "Hello world!".replace(/\s/g, '') + "'");
</script>

Which we would expect to output: Result: 'Helloworld!'

But in IE7 and IE8 though it fails using a non-breakable space like one of these: &#160; == &nbsp; == \u00A0

For example:

<script type="text/javascript">
document.write("Result: '" + String.fromCharCode(160).replace(/\s/g, '') + "'");
</script>

Will output Result: 'Helloworld!' in FF and IE >= 9 and Result : ' ' in IE7 and IE8. What the hell?

This makes me wonder if this is the only exception? I could not find much information about this at all. Is there maybe a Regular Expression which removes all white spaces including the non breakable?

like image 483
Yeti Avatar asked Nov 03 '22 12:11

Yeti


1 Answers

Use this one:

replace(/(?:\s|\xA0|&nbsp;|&#160;)+/g, '')

replace(/[\s\xA0]+/g, '')
like image 185
Ωmega Avatar answered Nov 15 '22 11:11

Ωmega