How use regexp replace in cycle for change text

时间:2018-07-24 10:11:58

标签: javascript

I have some array with regexp to replace in text.

Now I do

module.exports = (text) => {
    return text.replace( /smth/g, 'smth' )
        .replace( /smth/g, 'smth' );
};

But how I can iterates through the array

module.exports = (text) => {
    const exp = [
        ['smth', 'smth'],
        ['smth', 'smth'],
        ['smth', 'smth']
    ];

    return text.toLowerCase()
        .replace(translate[0][0], translate[0][1])
        .replace(translate[1][0], translate[1][1])
        .replace(translate[2][0], translate[2][1]);
}

Can I use forEach or map cycle?

2 个答案:

答案 0 :(得分:1)

You can simply use a for ... of loop on your expressions :

module.exports = (text) => {
    const exp = [
        ['smth', 'smth'],
        ['smth', 'smth'],
        ['smth', 'smth']
    ];

    let result = text.toLowerCase();
    for(let expression of exp) result = result.replace(expression[0], expression[1]);

    return result;
}

答案 1 :(得分:0)

Loop over the array, and apply the replace in each iteration:

return exp.reduce((text, [from, to]) => text.replace(from, to), exp.toLowerCase())

Working demo:

const text = 'the quick brown fox';

const exp = [
  ['the', 'wow'],
  ['brown', 'red'],
  ['fox', 'apple']
];

console.log(
  exp.reduce((text, [from, to]) => text.replace(from, to),
    text.toLowerCase())
);