last day (14 days later) » 

2:51 PM
-1
Q: Replace all occurrences in a string and avoid RegExp escaping

exebookIs that possible, without a loss of performance, to replace all occurrences of a substring with another string, and completely avoid using RegExp along the way? I.e. remove RegExp out of equation, just to make sure there is no RegExp magic happening when you forget to properly escape something li...

 
Of course you can loop until there's no more replacement done... But avoiding a regexp here looks really... not smart...
 
if you want to avoid regex then why a regex tag on your question?
 
because Regex is what I am trying to avoid
 
Would this solve your real problem ?
 
what's "not smart" about plain replacing of a string with a string?
 
2:51 PM
A regexp is just the right tool.
 
@dystroy unescaping programmatically is a performance hit
 
@exebook You want to avoid regexp and now you speak of performances ? You must be joking...
 
Nobody cares about premature optimization. Simple replacement and regex both work fine and have no real 'performance hit'.
 
@RoelvanUden, simple replacement is good, but it will only replace SINGLE occurence, not all.
 
"Doing programmatic unescape is a performance hit:" : compared to what solution ? Did you really measure ? If so cite your sources or link to your perf test
 
2:51 PM
'1+1 2+2'.replace('+', '-',"g") or "1+1 2+2".split("+").join("-")
 
It will still require multiple searches/replacements/copies if you loop. Using an escaped regex as in stackoverflow.com/questions/1144783/… works fine
 
@dystroy, you are right, the replace itself is fast, but you need an extra step: unescape, which takes extra time, especially noticable if done on small strings within a loop.
 
@mplungjan the split join solution is very slow, it can't be proposed as a solution to a performance problem.
 
I did not measure it. It is just an alternative.
 
there must be no solution to this problem, just have to accept it and unescape, either manual or programmatic.
 
2:51 PM
What do you mean by the "unescape step"? Surely it will just be treating \+ as a literal character?
 
@JamesThorpe, I just want to replace what I see with what I see, without thinking "ok, do I use another regexp control code here that I need to unescape?"
 
Right, so in the vein of a user doing a straight search/replace all type feature without the user needing to know about regular expressions? If that's the case, then I think you either have to bite the bullet and programmatically escape all special regex characters, or do a loop until the string is no longer found
 
@exebook I think you mean "escape". For instance if you want to replace backslashes with forward slashes using a RegExp, then you must escape the backslash characters.
 
@Brandin right, that's escape.
 

last day (14 days later) »