borsTiHD
borsTiHD

Reputation: 315

How can I replace all matches of a string?

I am trying to replace some sort of self made variables from multiple strings in an array. Later I will make a promp for the user to ask for the replacement, but in the first step I'm just trying to replace it with a 'test' value ('###').
Oh and I want it to be simplified (with the chained functions - I've only just discovered for myself and thats the problem here :D ). Can someone please help me?

What I got so far:

const replaceAll = (obj) => {
    obj.cmds.forEach((element, index, array) => {
        obj.cmds[index] = obj.cmds[index].match(/{.*?}/gmi).map((value) => {
            console.log('valuex', value)
            /*
            // Here the user should be asked for the replacement in the future.
            // const newValue = userPromp(value)
            */
            return obj.cmds[index].split(value).join('###')
        })
    })

    return obj
}

const newObj = replaceAll({
    name: 'ULTRA TEST',
    cmds: [
        'port {port}',
        'port {port} und random {random}',
        'random {random} und value {value}'
    ]
})

console.log(newObj)

Upvotes: 1

Views: 229

Answers (3)

Yone
Yone

Reputation: 976

i guess you need something like this

const replaceAll = obj => ({
  ...obj,
  cmds: obj.cmds.map(string => {
    let result = string;
    string.match(/{.*?}/gmi).forEach(template => { 
      // build <replace-string> here
      result = result.split(template).join('$$$'); 
    });
    return result; 
  })
}); 

const newObj = replaceAll({
    name: 'ULTRA TEST',
    cmds: [
        'port {port}',
        'port {port} und random {random}',
        'random {random} und value {value}'
    ]
})

console.log(newObj)

Upvotes: 1

Fallenreaper
Fallenreaper

Reputation: 10704

I think what you are looking for is something like this: You can see that instead of using match, i just use Replace and pass in the regex.

replaceAll = (obj) => {
    var m = {};
    obj.cmds.forEach((element, index, array) => {
        obj.cmds[index].match(/{.*?}/gmi).map( value => {
          var r = m[value]
          if (!r) { /* Create Prompt here. */ r = Math.random() * 10 }
          m[value] = r;
        })
        Object.keys(m).map( key => {
          obj.cmds[index] = obj.cmds[index].replace(key, m[key])
        });
    })

    return obj
}
newObj = replaceAll({
    name: 'ULTRA TEST',
    cmds: [
        'port {port}',
        'port {port} und random {random}',
        'random {random} und value {value}'
    ]
})

The json which is returned by newObj is:

{
  "name":"ULTRA TEST",
  "cmds":[
    "port 1",
    "port 1 und random 2",
    "random 2 und value 3"
  ]
}

So what will happen is that it will only prompt the user for values not previously prompted for in that iteration of replaceAll.

This will do exactly what you want.

Upvotes: 2

Shravan Dhar
Shravan Dhar

Reputation: 1560

You can use the inbuilt replace function. String.replace(/regex here/, <string to replace the matched regex>)

So for your case, I could do:

// take input here
let input = <input from user>

// string to replace with
let replacementString = "###"

for (let cmd of cmds) {
  cmd.replace(/`${input}`/gmi, replacementString);
}

Use for of instead of forEach as you cannot execute break in the latter. (Assuming you might want to have functionality of replacing one by one in the future).

Upvotes: 0

Related Questions