---
title: "js中的字符串替换"
author: "simple_hui"
date: "2009-10-29T14:43:48Z"
tags: []
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2012-09-09T13:43:05Z"
id: 506475
url: "https://simple-hui.iteye.com/blog/506475"
---

replace
语法 stringObj.replace(rgExp, replaceText)

replace 方法的语法包括下述部分：
部分 描述
stringObj  必选项。要执行该替换的 String 对象或文字。该对象不会被 replace 方法修改。 
rgExp  必选项。描述要查找的内容的一个正则表达式对象。 
replaceText  必选项。是一个String 对象或文字，对于stringObj 中每个匹配 rgExp 中的位置都用该对象所包含的文字加以替换。
例如：
1.只能替换第一个“a”字母
<script language="javascript">
var strM = "javascript is a good script language";
//在此我想将字母a替换成字母A
alert(strM.replace("a","A"));
</script>

2.可以替换所有“a”字母。其中g为全局标志
<script language="javascript">
var strM = "javascript is a good script language";
//在此将字母a全部替换成字母A
alert(strM.replace(/a/g,"A"));
</script>

3.在引用函数中所使用的将图片代码替换成表情符号

将所有的<img src="http://hikeimg.appspot.com/static/images/icon/icon_mrgreen.gif" >换成^~mrgreen~^

       //引用调用函数
       function quote(name,id){
        var quoteMsg=document.getElementById(id).innerHTML;
        var content=document.getElementById("comment");
        quoteMsg=quoteMsg.replace(/<IMG src=\"http:\/\/hikeimg.appspot.com\/static\/images\/icon\/icon_/g, "^~").replace(/.gif\">/g, "~^");
        content.value='引用'+name+'<blockquote>'+quoteMsg+'</blockquote>';
        return true;
       }