js实现"replaceAll"效果

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试</title>
</head>
<script type="text/javascript">
    function on_click(){
        var str = "你的我的它的";
        alert(replaceAll(str,/(的)/g, ""));
    }

    function replaceAll(str,reg1,reg2){
        return str.replace(reg1,reg2);//你我它
    }
</script>
<body >
    <input type="button" onclick="on_click()" value="点我"/>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在JavaScript中,有两个字符串方法可以用于替换字符串中的子串:`replace()`和`replaceAll()`。 1. `replace()`方法: `replace()`方法是字符串对象的方法,用于将指定的子串或正则表达式匹配的部分替换为新的字符串。它只会替换第一个匹配到的子串。 `replace()`方法的语法如下: ```javascript string.replace(searchValue, replaceValue) ``` 参数说明: - `searchValue`:要被替换的子串或正则表达式。 - `replaceValue`:用于替换的新字符串。 下面是一个示例用法: ```javascript const str = 'Hello, world!'; const newStr = str.replace('world', 'everyone'); console.log(newStr); // 输出: 'Hello, everyone!' ``` 在上面的示例中,`replace()`方法将字符串中的'world'替换为'everyone'。 2. `replaceAll()`方法: `replaceAll()`方法是字符串对象的方法,用于将所有匹配到的子串或正则表达式匹配的部分替换为新的字符串。它会替换所有匹配到的子串。 `replaceAll()`方法的语法如下: ```javascript string.replaceAll(searchValue, replaceValue) ``` 参数说明: - `searchValue`:要被替换的子串或正则表达式。 - `replaceValue`:用于替换的新字符串。 下面是一个示例用法: ```javascript const str = 'Hello, world!'; const newStr = str.replaceAll('o', 'e'); console.log(newStr); // 输出: 'Helle, werld!' ``` 在上面的示例中,`replaceAll()`方法将字符串中的所有'o'替换为'e'。 需要注意的是,`replace()`和`replaceAll()`方法都会返回一个新的字符串,并且原始字符串不会被修改。另外,`replace()`方法可以接受正则表达式作为`searchValue`参数,而`replaceAll()`方法在一些旧版本的JavaScript中可能不被支持,可以通过使用正则表达式和全局匹配来实现类似的效果

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值