js 字符串减去字符串_JS实现字符串中去除指定子字符串方法分析

本文实例讲述了JS实现字符串中去除指定子字符串方法。分享给大家供大家参考,具体如下:

Title

/*方法一:使用replace函数替换*/

//去除字符串中含有的某字符串:str = str.replace('give', '');

var str = 'Could you please give me a simple example of how to';

console.log("str=======前==" + str);//str=======前==Could you please give me a simple example of how to

//注意:此处不可写作:str.replace('give', '');要写作:str = str.replace('give', '');

// replace:返回新的字符串,一定要重新接收,不然替换不了

str = str.replace('give', '');//去掉字符的位置不定,可能在字符串中间,也可能在末尾

console.log("str.replace('give', '')==" + str.replace('give', ''));

//str.replace('give', '')==Could you please me a simple example of how to

console.log("str=======后==" + str);//str=======后==Could you please me a simple example of how to

/*方法二:使用字符串分割函数再聚合*/

var str = "hello world!";

var items = str.split("o");

//会得到一个数组,数组中包括利用o分割后的多个字符串(不包括o)

var newStr = items.join("");//数组转成字符串,元素是通过指定的分隔符进行分隔的。此时以空串分割:即直接连接

console.log("newStr=====" + newStr);// newStr=====hell wrld!

//会得到一个新字符串,将数组中的数组使用空串连接成一个新字符串

运行结果:

希望本文所述对大家JavaScript程序设计有所帮助。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值