替换字符串中的多次出现

时间:2019-06-26 10:57:52

标签: javascript

我想使用自定义字符替换用户输入中的某些单词。字符串将像这样

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: '='
    }]
var matchPunction = punctLists.find(tag => tag.name == userInput);
if (matchPunction) {
    userInput = matchPunction.tag;
}

但是它不起作用。 我想要这样的东西:

var userInput = "5+5 = 10*5";

有什么主意吗?

2 个答案:

答案 0 :(得分: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(' '))

答案 1 :(得分:2)

您可以将String.replace()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));