Im trying to replace words in string with matched key and index position without removing the other words.
My desired output is: hey HI hey HELLO
What i've tried so far...
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)
thanks for your help!
CodePudding user response:
A simple solution would be to use replace()
with a replacer function.
I use the regex /#(\D )(\d )/g
. Matching #
, followed by one or more non-digits (placed in capture group 1), followed by one or more digits (placed in capture group 2).
All capture groups are passed as arguments of the replacer function. The full match is passed as the first argument, capture group 1 as the second, etc.
Within the replacer function you can then access the value based on the captured attribute name and index.
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);
CodePudding user response:
you can use
- string.replace to replace the substr in the end of the process
- calculate the index in string array by recovered the last character of match string with
match[match.length - 1]
- recover category of data to use by removing first and last character
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)
CodePudding user response:
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)