Home >Web Front-end >JS Tutorial >A brief analysis of two methods of implementing replaceAll in js

A brief analysis of two methods of implementing replaceAll in js

零到壹度
零到壹度Original
2018-03-22 16:49:421618browse

This article mainly discusses two methods of implementing replaceAll in js. Friends in need can take a look at it. I hope it can help everyone.

js does not provide the replaceAll method, and using a for loop has efficiency issues. Use a regular expression as a solution

  • Method One

  • . String.prototype.replaceAll = function(s1,s2){ 
      return this.replace(new RegExp(s1,”gm”),s2); 
      }
  • Method Two

  • . string.replace(new RegExp(oldString,”gm”),newString)) 
      gm g=global, m=multiLine , 大致上方法就是这样的,可以实现替换全部指定字串

<span style='font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;'>If you don’t use regular expressions<br> str.replace(findStr, replaceStr) can only replace the first </span>

Related recommendations:

How to implement replaceAll in JS

String object extension replaceAll function in JavaScript

Detailed explanation of usage of replace and replaceAll

The above is the detailed content of A brief analysis of two methods of implementing replaceAll in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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