来源|||正则表达式|(RegularExpression)

  js 字符替换_js如何替换所有字符_js替换字符串中的字符

  来源 |

  [正则表达式]3是一门简单语言的语法规范js替换字符串中的字符,是强大、便捷、高效的文本处理工具,它应用在一些方法中,对字符串中的信息实现查找、替换和提取操作。

  JavaScript中的正则表达式用RegExp对象表示,有两种写法:一种是字面量写法;另一种是构造函数写法

  1、构造函数

  <pre style="text-align: left;"><pre class="code-snippet__js" data-lang="javascript">var reg=new RegExp(']+%>','g');</pre>

  2、字面量

  <pre style="text-align: left;"><pre class="code-snippet__js" data-lang="javascript">var reg=/]%>/g;</pre>

  g: global,全文搜索,默认搜索到第一个结果接停止

  i: ingore case,忽略大小写,默认大小写敏感

  m: multiple lines,多行搜索(更改^ 和$的含义js替换字符串中的字符,使它们分别在任意一行对待行首和行尾匹配,而不仅仅在整个字符串的开头和结尾匹配)

  JavaScript中正则表达式的使用

  一个正则表达式可以认为是对一种字符片段的特征描述,而它的作用就是从一堆字符串中找出满足条件的子字符串。比如我在JavaScript中定义一个正则表达式:

  <pre style="text-align: left;"><pre class="code-snippet__js" data-lang="javascript">var reg=/hello/ 或者 var reg=new RegExp("hello")</pre>

  那么这个正则表达式可以用来从一堆字符串中找出 hello 这个单词。而“找出”这个动作,其结果可能是找出第一个hello的位置、用别的字符串替换hello、找出所有hello等等。

  下面就列举一下JavaScript中可以使用正则表达式的函数。

  String.prototype.search方法

  用来找出原字符串中某个子字符串首次出现的index,没有则返回-1

  <pre style="text-align: left;"><pre class="code-snippet__js" data-lang="javascript">"abchello".search(/hello/); // 3</pre>

  String.prototype.replace方法

  用来替换字符串中的子串

  <pre style="text-align: left;"><pre class="code-snippet__js" data-lang="ruby">"abchello".replace(/hello/,"hi"); // "abchi"</pre>

  String.prototype.split方法

  用来分割字符串

  <pre style="text-align: left;"><pre class="code-snippet__js" data-lang="ruby">"abchelloasdasdhelloasd".split(/hello/); //["abc", "asdasd", "asd"]</pre>

  String.prototype.match方法

  用来捕获字符串中的子字符串到一个数组中。默认情况下只捕获一个结果到数组中,正则表达式有”全局捕获“的属性时(定义正则表达式的时候添加参数g),会捕获所有结果到数组中

  <pre style="text-align: left;"><pre class="code-snippet__js" data-lang="ruby">"abchelloasdasdhelloasd".match(/hello/); //["hello"]`"abchelloasdasdhelloasd".match(/hello/g); //["hello","hello"]`</pre>

  RegExp.prototype.test方法

  用来测试字符串中是否含有子字符串

  <pre style="text-align: left;"><pre class="code-snippet__js" data-lang="bash">/hello/.test("abchello"); // true</pre>

  RegExp.prototype.exec方法

  和字符串的match方法类似,这个方法也是从字符串中捕获满足条件的字符串到数组中,但是也有两个区别。

  1、exec方法一次只能捕获一份子字符串到数组中,无论正则表达式是否有全局属性

  <pre style="text-align: left;"><pre class="code-snippet__js" data-lang="javascript">var reg=/hello/g;`reg.exec("abchelloasdasdhelloasd"); // ["hello"]`</pre>

  2、 正则表达式对象(也就是JavaScript中的RegExp对象)有一个lastIndex属性,用来表示下一次从哪个位置开始捕获,每一次执行exec方法后,lastIndex就会往后推,直到找不到匹配的字符返回null,然后又从头开始捕获。 这个属性可以用来遍历捕获字符串中的子串。

  <pre style="text-align: left;"><pre class="code-snippet__js" data-lang="ruby">var reg=/hello/g;`reg.lastIndex; //0reg.exec("abchelloasdasdhelloasd"); // ["hello"]reg.lastIndex; //8reg.exec("abchelloasdasdhelloasd"); // ["hello"]reg.lastIndex; //19reg.exec("abchelloasdasdhelloasd"); // nullreg.lastIndex; //0`</pre>

  本文完~

  js如何替换所有字符_js替换字符串中的字符_js 字符替换

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/1504
0 评论
365

发表评论

!