Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple occurance in string

Tags:

javascript

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?

like image 319
Binita Gyawali Avatar asked Jun 26 '19 10:06

Binita Gyawali


2 Answers

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(' '))
like image 72
Ziv Ben-Or Avatar answered Nov 20 '22 17:11

Ziv Ben-Or


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));
like image 31
Fraction Avatar answered Nov 20 '22 18:11

Fraction