开发者

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 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜