brainwash
brainwash

Reputation: 689

Javascript: regex to replace some characters with their hexadecimal code

I haven't been able to find an example that does something similar to what I want, that is, replace:

% with %25

& with %26

/ with %2F

# with %23

" with space

\ with space

For the reference I'm using GWT with String.replaceAll, but I'm asking about Javascript since that is what it gets translated to anyway. I know about (component) URI encoding, but it's not what I'm after, I only need these characters.

Later edit: I'm looking for a way to do it in one or two regexes, right now it's done as this:

splits[i].replaceAll("%", "%25").replaceAll("&", "%26").replaceAll("/","%2F").replaceAll("#", "%23").replaceAll("\"", "").replaceAll("\\\\", " ");

but this seems ugly to me.

Upvotes: 1

Views: 8159

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075209

(This is for JavaScript, which is the language you asked about. Note that it will be fairly different in Java.)

In JavaScript, this is trivial using replace with a regular expression and passing in a function:

var str = "testing % & / # \" \\";
var result = str.replace(/[%&\/#"\\]/g, function(m) {
    return (m === '"' || m === '\\') ? " " : "%" + m.charCodeAt(0).toString(16);
});

Live example | source

If you don't mind scanning the string twice rather than once, it can look a bit simpler (though not enough that I think it's worth it):

var str = "testing % & / # \" \\";
var result = str.replace(/["\\]/g, " ").replace(/[%&\/#]/g, function(m) {
    return "%" + m.charCodeAt(0).toString(16);
});

...because we can do the " and \ replacement separately and get rid of the check for what we matched. Live example | source

Upvotes: 8

Denis Ermolin
Denis Ermolin

Reputation: 5556

String.replace(/%/, '%25').replace(/&/, '%26').replace(/\//, '%2F').replace(/#/, '%23').replace(/"/, ' ').replace(/\\/, ' ');

Upvotes: 0

Related Questions