博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

js替换字符指定字符方法

Posted on 2013-07-17 18:58  生命如风  阅读(1487)  评论(0编辑  收藏  举报


1、递归替换

function replaceChar(str, oldChar, newChar) {
if (str.indexOf(oldChar) != -1) {
str = str.replace(oldChar, newChar);
return replaceChar(str,oldChar, newChar);
}
else {
return str;
}
}


2、使用 replace RegExp 表达式
var date = '2012/4/8';
date = date.replace(new RegExp("/", "g"), '-'); 将‘/’替换成‘-’

RegExp语法 1
re = /pattern/[flags]

语法 2
re = new RegExp("pattern",["flags"])

参数
re

必选项。将要赋值为正则表达式模式的变量名。

Pattern

必选项。要使用的正则表达式模式。如果使用语法 1,用 "/" 字符分隔模式。如果用语法 2,用引号将模式引起来。

flags

可选项。如果使用语法 2 要用引号将 flag 引起来。标志可以组合使用,可用的有:

g (全文查找出现的所有 pattern)
i (忽略大小写)
m (多行查找)