Reputation: 2877
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 :)
Upvotes: 2
Views: 666
Reputation: 536597
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.
Upvotes: 6
Reputation: 523574
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.)
Upvotes: 4