Reputation: 256
I want to replace some of the words from the user's input using customized characters. The string will be like this
var userInput = "five plus five equal to ten multiply 5";
This is what I tried to do
const punctLists = {
name: 'star',
tag: '*'
},
{
name: 'bracket',
tag: ')'
}, {
name: 'multiply',
tag: '*'
}, {
name: 'plus',
tag: '+'
}, {
name: 'double equals',
tag: '=='
}, {
name: 'equal',
tag: '='
}]
var matchPunction = punctLists.find(tag => tag.name == userInput);
if (matchPunction) {
userInput = matchPunction.tag;
}
But it is not working. I want something like this :
var userInput = "5+5 = 10*5";
Any idea?
Upvotes: 6
Views: 90
Reputation: 12964
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));
Upvotes: 2
Reputation: 1194
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(' '))
Upvotes: 3