bianbian coding life

便便代码人生: 关注技术, 翻译文档, 偶尔动动手

[原] 关于正则表达式批量替换字符串解决方案答网友问

Posted by bianbian on 2008-04-20 15:43

本文Tags: , ,

发信人: Net (BBS上没有什么事情是bg不能解决的), 信区: WebDesign
标 题: Re: 如何使用正则分别替换?
发信站: 南京大学小百合站 (Sun Apr 20 15:21:23 2008)

不太可能一句话搞定,不过有相对而言的解决办法:
1) 简单易懂

  1. function arrayReplace(str, from, to) {
  2.   for(var i=0; i < from.length; i++)
  3.     str = str.replace(new RegExp(from[i], "g"), to[i]);
  4.   return str;
  5. }
  6. var from = ["A", "B", "C"], to = ["asdf", "fdsa", "......"];
  7. str = arrayReplace(str, from, to);

2) 勉强算一句话吧。。。

  1. str = str.replace(/(A|B|C)/g, function ($0, $1) {
  2.   return {"A": "asdf", "B": "fdsa", "C": "......"}[$1]
  3. });

【 在 superphoenix (格云朱雀) 的大作中提到: 】
: 比如要将一个字符串中的A替换为asdf,B替换成fdsa,C替换成……
: 能不能用一个正则话就替换成功?
: 而不是写成str=str.replace(/A/g,”asdf”).replace(/B/g,”fdsa”)….
: 谢谢!

※ 来源:.南京大学小百合站 bbs.nju.edu.cn.[FROM: Net.nEt.neT.Orz]

标签: , ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

(required)