Efficient way of replacing special characters

Suppose I have a string like this:

This is a fridge with 10 chocolates and ~5 icecream samples description to check if backward slash \ breaks anything and checking caret ^ symbol as well

I want to replace those special characters with the following:

\ to \1F 

~ to \7E

^ to \5E

I may find more to replace in future but at this point I just want to handle above such that after replacing it, the string looks like the following:

This is a fridge with 10 horse and \7E5 goat samples description to check if backward slash \F breaks anything and checking caret \5E symbol as well

Should I just follow the basic approach of finding if that special character exists in a string or not and then replace or if there’s any better way of handling this which I can scale it in future to accommodate new special characters?

replaceAll doesnt care if it’s in the string or not - you can run mystring.replaceAll("dog","cat") and if mystring doesnt have any “dog” in it you get… the original string back.

This does get a bit tedious if you have a lot of replacements to make though.

Perhaps the ‘shortest’ way i’ve seen it done is a replacement-object definition.

let replace = {
"\\" : "\\1F", //Note that this has to be \\, because you want a literal \.
"~": "\\7E",
"^": "\\5e"
mystring.replace(/[\\~^]/g,(m) => replace[m])


Thanks very much. I think the only thing not working is that it didn’t convert \ to \F in the final string. Any idea how can be fixed?

I"ve your example in JSFiddle here in case it’s easier to test.

The original string needs a \\ in it too. Javascript is eating it when you declare str.

I see. So even if user is going to type a single \ and that’s how it will get stored in the database. I should find all \ in the string first and then convert all \ to \\ before running your logic.

…depends on how you’re getting the data into Javascript? (If Javascript is directly interacting with the Database, their communication should transmit the \'s automatically; if you’re doing let data = <?= somePHPEchoingOfDataHere ?>, you’ll need to stick some extra 's in somewhere.

Hmm. It’s coming back to the user interface from a Java web service so I might just have to create the string again by finding \ and then replacing it with \\. That adds an additional character as well I believe and I may have to think what to do since I’ve 250 characters limit and if it goes above that after running the logic.

Well, give it a try as-is, and if you’re missing characters when you output it, you know you need to add slashes somewhere :slight_smile:

1 Like