I have a rather complex regular expression that matches a few strings. As part of the requirement, I need to replace some of the matching text with a truncated version. Using a backreference I get the text, but how do I use "string".replace() to truncate it e.g. only the first 10 characters? As there may be multiple matches per string, I do not want to manually extract and truncate the text.
In Javascript 1.3 it's possible to pass a function as the replacement argument:
s = s.replace(/someregularexpression/g, function(x){ return x.substr(0, 10); });
(source)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With