Home > Web Front-end > JS Tutorial > body text

How to remove specific characters in javascript

醉折花枝作酒筹
Release: 2021-07-20 11:05:22
Original
5723 people have browsed it

The method of removing specific characters in JavaScript is: 1. Use the replace function to replace, the syntax is "element.replace('String to be removed', '')"; 2. Use the string splitting function and then aggregate.

How to remove specific characters in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

The example in this article describes the JS method of removing specified substrings from strings. Share it with everyone for your reference, the details are as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script>
  /*方法一:使用replace函数替换*/
  //去除字符串中含有的某字符串:str = str.replace(&#39;give&#39;, &#39;&#39;);
  var str = &#39;Could you please give me a simple example of how to&#39;;
  console.log("str=======前==" + str);//str=======前==Could you please give me a simple example of how to
  //注意:此处不可写作:str.replace(&#39;give&#39;, &#39;&#39;);要写作:str = str.replace(&#39;give&#39;, &#39;&#39;);
  // replace:返回新的字符串,一定要重新接收,不然替换不了
  str = str.replace(&#39;give&#39;, &#39;&#39;);//去掉字符的位置不定,可能在字符串中间,也可能在末尾
  console.log("str.replace(&#39;give&#39;, &#39;&#39;)==" + str.replace(&#39;give&#39;, &#39;&#39;));
  //str.replace(&#39;give&#39;, &#39;&#39;)==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>
Copy after login

Running results:

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to remove specific characters in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template