簡體   English   中英

一種更好的方法,而不是在JavaScript中使用字符串替換

[英]A better approach instead of using String replace in javascript

我正在嘗試對匹配正則表達式的字符串數組的每個元素進行一些操作。

我已經能夠通過使用replace函數解決此問題:

const anyRegExp = new RegExp('string[(\d)]');
const sampleArr = ['string[1].name','string[2].name' /*,...*/]
const myOp1 = (...args) => /* operations */
const myOp2 = (...args) => /* different operations */
sampleArr.forEach(key => key.replace(anyRegExp, (par1, par2, par3, par4) => {
  console.log(par1, par2, par3, par4);
  // prints: 'string[1]', '1', 1, 'string[1].name'
  //         'string[2]', '2', 2, 'string[2].name'
  if (par3 > 1) {
    myOp(par1,par2,par3,par4);
  } else {
    myOp2(par1,par2,par3,par4);
  }
}));

如您所見,我根本不需要真正的替換操作。 我知道它無論如何都不會修改我的密鑰,我只是想知道在String中是否定義了任何其他種類的函數更適合此工作。

我嘗試了match,但是它沒有收到作為第二個參數的函數。

輸出樣本(使用谷歌瀏覽器)

const temp1 = /Tests.MyTests\[(\d+)\]/
const temp2 = "Tests.MyTests[0].name"

temp2.match(temp1, (...args) => console.log('args',args))
 outputs--> ["Tests.MyTests[0]", "0"]

temp2.replace(temp1, (...args) => console.log('args',args))
 logs--> args ["Tests.MyTests[0]", "0", 0, "Tests.MyTests[0].name"]
 outputs--> "undefined.name"

可以看出,replace接收了一個函數,該函數為我提供了4個參數,這是我要使用的參數。

匹配不記錄任何內容

 const temp1 = /Tests.MyTests\\[(\\d+)\\]/ const temp2 = "Tests.MyTests[0].name" temp2.match(temp1, (...args) => console.log('args',args)); 

 const temp1 = /Tests.MyTests\\[(\\d+)\\]/ const temp2 = "Tests.MyTests[0].name" temp2.replace(temp1, (...args) => console.log('args',args)) 

您可能正在尋找

for (let key of sampleArr)
    myOp(...key.match(anyRegExp)) // or anyRegExp.exec(key)

假設正則表達式始終匹配整個字符串,而不是部分匹配多次

您可以使用split然后join ,例如,您想將任何符號字符regex替換為“-”,然后

myString.split(/[^\\w-]/).join('-')

暫無
暫無

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

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