簡體   English   中英

從javascript中的字符串數組替換字符串上的某些字符

[英]Replace certain character on string from an array of string in javascript

我有一個這樣的字符串

const text = 'hello ___ where ___ test ___'

還有這樣的數組

const blankData = ['there', 'you', 'it']

我的預期結果是

hello there where you test it

我試過的

const result = text?.replaceAll('___', (index, x) => {
    return blankData[index]
  })

我也有這樣不優雅的想法

const mapped = text
    .split('___')
    .map((textitself, index) => textitself + blankData?.[index])

  mapped.pop()

 const result = mapped.join('')

有更好的解決方案嗎?

我正在考慮獲取索引,這樣我就可以為找到的每個索引進行替換,但替換不會從中獲取索引回調

您可以使用/g標志全局匹配___並從blankData獲取替換的索引,將blankData設為 0 並在每次迭代中增加它。

 const text = 'hello ___ where ___ test ___'; const blankData = ['there', 'you', 'it']; result = text.replace(/___/g, (i => _ => blankData[i++])(0)); console.log(result);

請注意,如果您不想對_________進行多個匹配,但也不想匹配單個_ ,則可以使用_{3,}作為模式來匹配 3 次或多次下划線。

 const text = 'h_ello ______ where ___ test ___'; const blankData = ['there', 'you', 'it']; result = text.replace(/_{3,}/g, (i => _ => blankData[i++])(0)); console.log(result);

您可以在這里使用replace ,您可以在replacereplaceAll方法之外聲明index

您已經對替換字符串___進行了硬編碼,如果還有一個_怎么辦,那么您可以使用one or more _量詞_+使其通用

在此處輸入圖片說明

 const text = "hello ___ where ___ test ___"; const blankData = ["there", "you", "it"]; let index = 0; const result = text.replace(/_+/g, () => blankData[index++]); console.log(result);

您也可以使用 replaceAll 但您只需要處理索引

 const text = "hello ___ where ___ test ___"; const blankData = ["there", "you", "it"]; let index = 0; const result = text?.replaceAll("___", () => { return blankData[index++]; }); console.log(result);

我已經為此做了一個功能。 我認為代碼是不言自明的。

 function injectStrings(string, replacementsArr) { var pattern = /___/g, replacement = ''; return string.replace(pattern, function(match) { replacement = replacementsArr.shift(); if (typeof replacement == 'number' || typeof replacement == 'string') { return replacement; } // console.log('parameter for ' + match + ' is missing in \\"' + string + '\\"'); return ''; }); } const text = 'hello ___ where ___ test ___' const blankData = ['there', 'you', 'it'] // output: And also an array like this console.log( injectStrings(text, blankData) );

暫無
暫無

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

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