JS中常见的replace


在学习JS时遇到了replace,很容易混淆,于是总结下来供大家参考,它们分别在字符串,classList,节点中出现过

1.字符串中的replace

语法:string.replace(“被替换的字符串old” , “替换的字符串new”),代码如下(示例):

<script>
	var a = "123我没K";
	var b = a.replace("我没K", "布鲁biu");
	console.log(a, b);
</script>

2.classList中replace

语法:节点.classList.replace(“被替换的类名old” , “替换的类名new”),代码如下(示例):

<div class="box1 box2 box3"></div>
<script>
    var box = document.querySelector(".box1");
    console.log(box.classList);//'box1', 'box2', 'box3'
    box.classList.replace("box2", "2box");
    console.log(box.classList);//'box1', '2box', 'box3'
</script>

3.DOM操作节点中的替换

语法:父节点.replaceChild(替换的子节点new , 被替换的子节点old),代码如下(示例):

<div class="box1 box2 box3">
    <span>special text</span>
</div>
<script>
    var box = document.querySelector(".box1");
    var span = document.querySelector("span");
    var strong = document.createElement("strong");
    strong.innerHTML = "我是替换的strong标签";
    console.log(box.innerHTML);//<span>special text</span>
    box.replaceChild(strong, span);
    console.log(box.innerHTML);//<strong>我是上场的strong标签</strong>
</script>

注意

第三个DOM操作节点中的替换语法中后面括号中是new在前,old在后。
这个地方与前两个语法有所不同。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值