javascriptregexstringreplacelpcstr

How to efficiently replace characters within a string, which may repeat


I'm writing a string formatting function in LPC (...), but am versed in Javascript so a solution in either would be fine, the problem I am having is taking the following string for example:

~~~abc~~de~~~~~~~~~~~fgh~

And wrapping each ~ in a set of characters, for example []. My current output, using a standard replace_string() method, is:

[~][~][~]abc[~][~]de[~][~][~][~][~][~][~][~][~][~][~]fgh[~]

Where my goal is to output:

[~~~]abc[~~]de[~~~~~~~~~~~]fgh[~]

The reason I need to address this is because of max string length limitations, so it's actually an optimisation I need as opposed to one that would be a nice-to-have.

cheers, d


Solution

  • Use capturing group ((...)) and backreference ($1)

    '~~~abc~~de~~~~~~~~~~~fgh~'.replace(/(~+)/g, '[$1]')
    // => "[~~~]abc[~~]de[~~~~~~~~~~~]fgh[~]"