开发者

Limit length of backreference in Javascript regular expression

开发者 https://www.devze.com 2023-02-06 19:48 出处:网络
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

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 trunc开发者_运维问答ate 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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号