![](/img/trans.png)
[英]How to extract values from an object and return it in an array of strings with specific requirements
[英]How to extract a specific substring (based on regex) from an array of strings
我有一大串字符串:
['{{Wanted Value}}', 'true', '{{Wanted Value}}', '{{Wanted Value}} unwanted {{Wanted Value}}', 'false'...]
我想過濾數組並將每個{{Wanted Value}}
子字符串提取到一個新數組中。 如果數組中的項目包含 2 個或更多這些子字符串,我希望將它們中的每一個作為單獨的項目。 所以上述數組的結果是:
['{{Wanted Value}}', {{Wanted Value}}', {{Wanted Value}}', {{Wanted Value}}']
我編寫了我想使用的正則表達式,但不確定如何正確編寫過濾器函數:
match(/\{\{(.+?)\}\}/)[0]
謝謝
你可以試試這個方法
flatMap
是收集所有匹配的字符串filter
是去除空結果 const data =['{{Wanted Value}}', 'true', '{{Wanted Value}}', '{{Wanted Value}} unwanted {{Wanted Value}}', 'false'] const result = data.flatMap(stringData => stringData.match(/\{\{(.+?)\}\}/g)).filter(stringData => stringData); console.log(result)
這是一個使用reduce
和字符串match
函數來過濾結果的代碼
let r = ['{{Wanted Value}}', 'true', '{{Wanted Value}}', '{{Wanted Value}}', 'unwanted','{{Wanted Value}}', 'false']; const result = r.reduce((accumulator, current) => { return current.match(/\{\{(.+?)\}\}/)? accumulator.concat(current): accumulator; }, []); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.