Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

前端正则匹配

想匹配到 已千米 为结尾的所有非数字字符
例如: let str = '123ja23x千米x123x千米'

 最后想得到是  12323123千米

 我的写法是
 let reg = /D+[^(千米)$]/g
 str.replace(reg, '')
 结果 : 123323x千米

 但是不对  想请教一下 怎么写


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

1 Answer

0 votes
by (71.8m points)

相当于把非数字字符清除,但是被清除的字符后面不能是,也不能是结束符$

'123ja23x千米x123x千米'.replace(/D(?!米?$)/g, ''); // 12323123千米

不过可读性稍稍差了些,还不如'123ja23x千米x123x千米'.replace(/D/g,'') + '千米'更直接些。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...