0

I didn't find my answer in old StackOverflow questions, so I have an array that contains some words, also I have a long string that has the same word as in the array.

Now, I want to add a prefix to words that has $, for example, I want to change all $status to $prefix_status

This is what I test, but replaceAll doesn't replace anything.

const myPrefix = 'prefix'
const array = ['status', 'id', 'offset', 'limit'];
const string = '($status: CardStatus, $id: ID, $offset: Int, $limit: Int), (status: $status, id: $id, offset: $offset, limit: $limit)';

array.forEach((i) => {  
  string.replaceAll(`$${i}:`, `$${myPrefix}_${i}:`)
})

NOTE: if I write replaceAll('$status:', `$${myPrefix}_${i}:`) it works, but it seem replaceAll doesn't accept variables as its first argument.

Ari Shojaei
  • 361
  • 5
  • 12
  • 2
    `replaceAll` returns a new string, it does not mutate the string in-place. It cannot, since strings are immutable. You need to get the result of calling the method `string = string.replaceAll()`. That also means `string` should not be a `const`. The [result of your code](https://jsbin.com/hunajoviwe/edit?js,console) is `"($prefix_status: CardStatus, $prefix_id: ID, $prefix_offset: Int, $prefix_limit: Int), (status: $status, id: $id, offset: $offset, limit: $limit)"` – VLAZ Oct 19 '21 at 09:32
  • 1
    try this, `const result = string.replace(new RegExp('\\$((' + array.join('|') + '))', 'g'), '$prefix_$1')` – ProDec Oct 19 '21 at 09:38
  • thanks @VLAZ your comment helped me to figure it out the problem – Ari Shojaei Oct 19 '21 at 09:39

0 Answers0