Rumah  >  Artikel  >  hujung hadapan web  >  怎样使用JS做出字符串内去除指定子字符串

怎样使用JS做出字符串内去除指定子字符串

php中世界最好的语言
php中世界最好的语言asal
2018-05-29 10:03:051962semak imbas

这次给大家带来怎样使用JS做出字符串内去除指定子字符串,使用JS做出字符串内去除指定子字符串的注意事项有哪些,下面就是实战案例,一起来看一下。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script>
  /*方法一:使用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!
  //会得到一个新字符串,将数组中的数组使用空串连接成一个新字符串
</script>
</body>
</html>

运行结果:

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

如何对于create-react-app修改为多页面支持

如何使用nodejs 服务器读取HTML文件渲染至前端

Atas ialah kandungan terperinci 怎样使用JS做出字符串内去除指定子字符串. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn