6

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?

3
  • What is text here in text = matchPunction.tag; ? Commented Jun 26, 2019 at 11:17
  • @SudhirOjha, thanks, that was type, which is edited Commented Jun 26, 2019 at 11:30
  • Your question in incomplete add name for five and ten as well Commented Jun 26, 2019 at 11:33

2 Answers 2

3

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(' '))

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mate. This is what I wanted.
@Fraction, i basically want to replace with the lists in punctLists. equal to will be in the list
2

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.