簡體   English   中英

如何使用 string.prototype.matchall polyfill?

[英]How to use the string.prototype.matchall polyfill?

我希望String.prototype.matchAll()方法也可以在邊緣瀏覽器中工作。 於是想到了使用“string.prototype.matchall”npmjs package

我已經安裝了這個 package 並像這樣導入到我的main.js文件中

import 'string.prototype.matchall';

我必須在其他文件中使用這個方法,比如Input.js. 所以我使用如下

const matchAll = require('string.prototype.matchall');

在我實際匹配字符串的方法中,如下

replace = (original_string) => {
  const regex_pattern = /\\d+@*)]/g;
  const matchAll = require('string.prototype.matchall'); 
  const matches = original_string.matchAll(regex_pattern);
  return matches;
}

matchAll變量未使用。 如何使用這個string.prototype.matchall polyfill 有人可以幫我解決這個問題嗎? 謝謝。

因為 package 實現了es-shim API ,所以您應該調用shim()方法...

require('foo').shimrequire('foo/shim')是一個 function ,調用時會調用getPolyfill ,如果 polyfill 與內置值不匹配,會將其安裝到全局環境中。

這將讓您使用String.prototype.matchAll()

const matchAll = require('string.prototype.matchall')
matchAll.shim()

const matches = original_string.matchAll(regex_pattern)

否則,您可以單獨使用它

require('foo')是符合規范的 JS 或原生 function。 但是,如果函數的行為取決於接收器(“this”值),則此 function 的第一個參數將用作該接收器。 package 應在其自述文件中指出是否屬於這種情況

const matchAll = require('string.prototype.matchall')

const matches = matchAll(original_string, regex_pattern)

要使用 ES6 模塊導入,您可以在腳本頂部使用類似這樣的內容(不在replace函數中)

import shim from 'string.prototype.matchall/shim'
shim()

我用過這個,對我有用。 循環遍歷全局標記模式的匹配就可以了。 如果您在使用它時遇到任何問題,請告訴我,我很樂意為您提供幫助。

function matchAll(pattern,haystack){
    var regex = new RegExp(pattern,"g")
    var matches = [];
    
    var match_result = haystack.match(regex);
    
    for (let index in match_result){
        var item = match_result[index];
        matches[index] = item.match(new RegExp(pattern)); 
    }
    return matches;
}

您還可以使用exec RegExp方法。

function matchAll(re, str) {
  let match
  const matches = []

  while (match = re.exec(str)) {
    // add all matched groups
    matches.push(...match.slice(1))
  }

  return matches
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM