Replace string by schema inside array

I want to change myString by mobiles schema.
myString = "Samsung, Google, Apple ";
myNewString = 'Galaxy Note 9, Pixel 3, iPhone X'
How to do that?

const mobiles = [
    {
        oldWord: 'Samsung',
        newWord: 'Galaxy Note 9'
    },
    {
        oldWord: 'Google',
        newWord: 'Pixel 3'
    },
    {
        oldWord: 'Apple',
        newWord: 'iPhone X'
    }
];

var myString = "Samsung, Google, Apple ";

I try something like this, but I can't understood what is wrong in my code.

[{"id":"3179b52506f8de37","type":"function","z":"43fcf7fcdce59eff","name":"","func":"const mobiles = [\n    {\n        oldWord: 'Samsung',\n        newWord: 'Galaxy Note 9'\n    },\n    {\n        oldWord: 'Google',\n        newWord: 'Pixel 3'\n    },\n    {\n        oldWord: 'Apple',\n        newWord: 'iPhone X'\n    }\n];\n\nvar myString = \"Samsung, Google, Apple \";\nvar reg = new RegExp(oldWord, \"gi\");\n\nvar oldWord = '';\nvar newWord = '';\n      \nmyString = myString.replace(reg, newWord);\nvar myNewString = '';\n       \nmobiles.forEach(mobile => {\n    for (let key in mobile) {\n      //  console.log(`${key}: ${mobile[key]}`);\n      oldWord = key;\n      newWord = mobile[key];\n      myNewString = myString.replace(reg, newWord);\n        node.send({\n                      myString: myString,\n                      myNewString: myNewString\n                      \n\n                        });\n    }\n});\n\nreturn null;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":300,"y":560,"wires":[["dc4ef151051e87b6"]]},{"id":"d525d7417bf00397","type":"inject","z":"43fcf7fcdce59eff","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":130,"y":560,"wires":[["3179b52506f8de37"]]},{"id":"dc4ef151051e87b6","type":"debug","z":"43fcf7fcdce59eff","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":470,"y":560,"wires":[]}]

chrome_227WfLQMLA

function code...

const mobiles = [
    {
        oldWord: 'Samsung',
        newWord: 'Galaxy Note 9'
    },
    {
        oldWord: 'Google',
        newWord: 'Pixel 3'
    },
    {
        oldWord: 'Apple',
        newWord: 'iPhone X'
    }
];

let result = msg.payload;
mobiles.forEach(e => {
    const searchRegExp = new RegExp(e.oldWord, 'gi'); 
    result = result.replace(searchRegExp, e.newWord);
})

msg.payload = result;

return msg;
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.