我試圖用匹配的鍵和索引位置替換字串中的單詞而不洗掉其他單詞。
我想要的輸出是:嘿嘿嘿嘿
到目前為止我嘗試過的...
var data = {
items: ["item", "HI", "item2"],
moreitems: ["moreitem", "moreitem1", "HELLO"]
}
var str = "hey #items1 hey #moreitems2";
var newStr = '';
var match = str.match(/#(.*?)\d /g); //get str that starts with # and ends with digits
for (var i = 0; i < match.length; i ) {
var keys = match[i].replace(/#|\d /g, ''), // remove hash and numbers to match the data keys
pos = match[i].replace(/\D/g, ''); // get the digits in str
newStr = data[keys][pos] ' ';
}
console.log(newStr)
感謝您的幫助!
uj5u.com熱心網友回復:
一個簡單的解決方案是使用replace()替換函式。
我使用正則運算式/#(\D )(\d )/g。匹配#,后跟一個或多個非數字(放置在捕獲組 1 中),后跟一個或多個數字(放置在捕獲組 2 中)。
正則運算式
所有捕獲組都作為替換函式的引數傳遞。完整匹配作為第一個引數傳遞,捕獲組 1 作為第二個引數,等等。
然后,在替換函式中,您可以根據捕獲的屬性名稱和索引訪問值。
var data = {
items: ["item", "HI", "item2"],
moreitems: ["moreitem", "moreitem1", "HELLO"]
}
var str = "hey #items1 hey #moreitems2";
const result = str.replace(
/#(\D )(\d )/g,
(_match, attr, index) => data[attr][index]
);
console.log(result);
uj5u.com熱心網友回復:
您可以使用
- string.replace 在行程結束時替換 substr
- 通過恢復匹配字串的最后一個字符來計算字串陣列中的索引
match[match.length - 1] - 通過洗掉第一個和最后一個字符來恢復要使用的資料類別
category = match.slice(0, -1).substring(1);
var data = {
items: ["item", "HI", "item2"],
moreitems: ["moreitem", "moreitem1", "HELLO"]
}
var str = "hey #items1 hey #moreitems2";
var newStr = str;
var match = str.match(/#(.*?)\d /g);
var index, category;
console.log(match);
match.forEach(match => {
index = match[match.length - 1];
category = match.slice(0, -1).substring(1);
newStr = newStr.replace(match, data[category][index]);
});
console.log(newStr)
uj5u.com熱心網友回復:
const dic = {
xxx: 'hello',
yyy: 'world',
zzz: 'peace'
}
const string = 'hey! #xxx, #yyy! #zzz on you'
const newString = string.replace(/#\w /g, item => dic[item.substring(1)])
console.log(string)
console.log(newString)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/451942.html
標籤:javascript 数组 代替
上一篇:在JavaScript中解構元組
下一篇:用物件修改陣列
