---
title: "JS正则表达式怎样实现Java中String.replaceAll的效果"
author: "coding1688"
date: "2013-02-07T08:41:42Z"
tags: []
categories: ["Web前端"]
slug: "js-java-string-replaceall"
draft: false
lastmod: "2013-02-07T08:41:42Z"
id: 1797189
url: "https://coding1688.iteye.com/blog/1797189"
---

在JavaScript中，使用String对象的replace方法时，会发现使用字符串直接量作为被替换对象时，只会替换第一个匹配的字符串，其余的匹配字符串保持不变。比如下面的代码，content中的第一个“营销”会被替换，但第二个不会：

```
    var content = "营销管理系统，主要进行营销管理";
    var replaced = content.replace("营销", "销售");
```

　　那么，要实现像Java中的String类的replaceAll那样进行全部替换要怎么做呢？答案是使用正则表达式进行字符串的全局替换。如下代码所示，实现了输入查找内容和替换后文本，然后执行全局替换。（注意使用了FreeMarker代码）

```
    $("#replace_${comitem.comitemId}_${field.fieldId}").click(function(){
        var content = $("#form${form.formId}_${field.fieldIdRow.sysName}").val();
        if (content) {      
            var oldText = prompt("请输入查找内容：", "");
            if (oldText) {  
                var newText = prompt("替换为：", oldText);
                if (newText && newText != oldText) {
                    var replaced = content.replace(new RegExp(oldText, "g"), newText);
                    $("#form${form.formId}_${field.fieldIdRow.sysName}").val(replaced);
                    Eap.alert("已将【" + oldText + "】替换为【" + newText + "】");
                }   
            }           
        }                   
    });     


```

　　你也可以看看下面这几篇文章：  
　　(1)  [JS中实现replaceAll的方法](http://fuleonardo.iteye.com/blog/339749)（http://fuleonardo.iteye.com/blog/339749）  
　　(2) [JavaScript正则表达式：用String.replace()方法进行字符串替换](http://www.vktone.com/articles/js-regexp-string-replace.html)

 

- 源文【JS正则表达式怎样实现Java中String.replaceAll的效果】最新版，请访问：  
     [http://www.vktone.com/articles/js-regexp-replaceall.html](http://www.vktone.com/articles/js-regexp-replaceall.html)