views:

56

answers:

2

Hi,

i have made an app,

you write some text, and text will be saved over ajax. Before sending the request, i escaped it with js. But somehow, the "+" Character will be converted to " " Space Character...

So i tryed to find and replace before sending in "%plus%" but i get thes error message:

Uncaught SyntaxError: Invalid regular expression: /+/: Nothing to repeat

Code:

var replace = "%plus%";
            while(title.search(sign) != -1) {
               title.replace("+", replace);
            }

Maybe some one know a better solution for this... i work with utf-8... and german characters like "ä" I have also Problems with "€" while getting it from DB over Ajax... and a lot other characters....

I have great results if i rawescape() in php and unescape() in js (but still have Problems with € -> %u20AC

Need help :)

+4  A: 

To match a + in regex, you need to escape it because + itself is a special character.

return theText.replace(/\+/g, "%plus%");

BTW, the proper encoding of + is %2b. You could use encodeURIComponent for this, in Javascript. (Don't use escape, it's deprecated.)

KennyTM
encodeURIComponent this ist the solution for my Problem! thx.
Fincha
but now i have problems with german characters, what a function a have to use in php?
Fincha
@Fincha: What problem?
KennyTM
How do i encode the string in PHP correctly? If I do not encode, i get this A+B = öäü ? à from "A+B = öäü ? ß"Have you an idea?
Fincha
@Fincha: I don't know what you mean. Maybe you should ask a new question.
KennyTM
+4  A: 

So i tryed to find and replace before sending in "%plus%"

That is insufficient. If you're failing to URL-encode the + symbol, you are almost certainly forgetting to URL-encode anything, and there are many other characters that will cause failure if not URL-encoded than just the plus sign.

You need to use encodeURIComponent() when creating your request to encode special characters inside parameters:

var url= 'something?param='+encodeURIComponent(param)+'&other='+encodeURIComponent(other);

Otherwise, any characters that don't fit in URLs will cause corruption, including + (which means a space if included in a query parameter; for a real plus sign you'd need %2B) and many other punctuation symbols, as well as all non-ASCII characters (eg. should be %E2%82%AC, using UTF-8 encoding).

Do not under any circumstances use the JavaScript escape() and unescape() functions. These are not URL-encoding, but a non-standard encoding peculiar to JavaScript that looks similar to URL-encoding but is not compatible. In particular all non-ASCII characters get mutilated, which is why wouldn't work.

bobince