Replace multiple occurance in string
var userInput = "five plus five equal to ten multiply 5";
const punctLists = [
{ name: "star", tag: "*" },
{ name: "bracket", tag: ")" },
{ name: "multiply", tag: "*" },
{ name: "plus", tag: "+" },
{ name: "double equals", tag: "==" },
{ name: "equal", tag: "=" },
{ name: "five", tag: "5" },
{ name: "ten", tag: "10" }
];
console.log(userInput
.split(' ')
.map(x => (f = punctLists.find(item => item.name == x)) && f.tag || x)
.join(' '))
You can use String.replace()
with a RegExp
:
const userInput = "five plus five equal to ten multiply 5";
const punctLists = [
{name: 'star', tag: '*'},
{name: 'bracket', tag: ')'},
{name: 'multiply', tag: '*'},
{name: 'plus', tag: '+'},
{name: 'double equals', tag: '=='},
{name: 'equal to', tag: '='},
{name: 'five', tag: '5'},
{name: 'ten', tag: '10'}
];
function ReplaceText(input) {
return punctLists.reduce((acc, a) => {
const re = new RegExp(a.name,"g");
return acc.replace(re, a.tag);
}, input);
}
console.log(ReplaceText(userInput));