jolt jolt - 4 months ago 11
Javascript Question

trim() not catching AJAX posted data value of  

I have a

contenteditable
element, that
onblur
posts it's value to server.

Because it's a
contenteditable
, upon repeated space entries, instead of blank space, it adds
 
instead, so the resulting HTML can be:

Testing title   middle   entry    


That when retrieved with
.text()
from element, looks like normally spaced (underlines mark spaces):

Testing_title___middle___entry____


This
.text()
value I am posting over to my PHP backend. There I go through the saving procedure. Because I need the string trimmed, a basic
trim($title)
didn't cut it.

And, I cannot seem to get my head around it.

I have tried also this How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?, didn't help either.

Chrome Network inspector, shows it sends over this encoded data:

Testing+title+%C2%A0+middle+%C2%A0+entry+%C2%A0+%C2%A0


implode(', ', unpack('C*', $title))
returns:

84, 101, 115, 116, 105, 110, 103, // Testing
32, // space
116, 105, 116, 108, 101, // title
32,
194, 160, //  
32,
109, 105, 100, 100, 108, 101, // middle
32,
194, 160,
32,
101, 110, 116, 114, 121, // entry
32,
194, 160,
32,
194, 160


$title
ultimately is just a
$_POST['title']
.

How do I trim all whitespaces from this string?




FINALLY, THE SOLUTION WAS:

$title = preg_replace('/\s/iu', ' ', $title)

Answer

How about replacing all   with spaces before you start trimming?

$text= str_replace(' ', ' ', $text)

Or, if you want to remain unicode safe, you can use mb_eregi_replace http://www.php.net/manual/en/function.mb-eregi-replace.php

EDIT - Second approach:

According to this answer (http://stackoverflow.com/a/13992998/486780)

194 160 is the UTF-8 encoding of a NO-BREAK SPACE codepoint (the same codepoint that HTML calls  ).

So it's really not a space, even though it looks like one. (You'll see it won't word-wrap, for instance.) A regular expression match for \s would match it, but a plain comparison with a space won't.

Try using regexp to match for it as suggested above?

Comments