简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM