Lennart
Lennart

Reputation: 111

React: find string in array and rename it

How can I rename an element of an array if this element contains a given string?

So e.g. I have an array in my state:

constructor(props) {
        super(props);
        this.state = {
            array: ["stack", "overflow", "question"],
        }
}

and now I wanna replace the string question with e.g. answer. So I could easily do this if the index of question is always the same but how can I replace question with answer if question always have an other index? This should be done in the most efficient way. Hope anyone can help me. Thanks

Upvotes: 1

Views: 1159

Answers (2)

Rob Bailey
Rob Bailey

Reputation: 981

You could use indexOf to find out what index the item is at and then replace that.

Something like:

const arr = ["stack", "overflow", "question"];

function replaceStr(newStr, str, arr){
  if(arr.indexOf(str) >= 0){
    arr[arr.indexOf(str)] = newStr;
  }
  return arr;
}

console.log(replaceStr("Hello", "question", arr))

Upvotes: 1

Vivek Doshi
Vivek Doshi

Reputation: 58573

HERE YOU GO :

This is just a code snippet, you can apply your logic as well, I have just compare exact string for simplicity of code.

console.log(
        ["stack", "overflow", "question"]
        .map(str => str==="question" ? "answer" : str)
)


In react, you can use it like

this.setState((state) => {
    array : state.array.map(str => str==="question" ? "answer" : str)
})

Upvotes: 5

Related Questions