Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit length of backreference in Javascript regular expression

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.

like image 294
Michael Avatar asked May 20 '26 12:05

Michael


1 Answers

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)

like image 156
Mark Byers Avatar answered May 23 '26 01:05

Mark Byers