Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

字符串多个 replace 如何写性能更高?

string
.replace(/a/g, '!')
.replace(/b/g, '#')
.replace(/c/g, '没规律的')
.replace(/d/g, '没规律的')
.replace(/e/g, '没规律的')
// 以下省略20行
.....

以上,像这种字符串替换,源文本很大、高频率调用的情况下

如何写怎么省内存和提高性能呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
let mapReplace = {
    'a' : '!',
    'b' : '#',
    'c' : '没规律的',
    'd' : '没规律的',
};
<string>.replace(/a|b|c|d/g, function($match){
   if($match in mapReplace === true)
       return mapReplace[$match];
       
   return $match;
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...