Nagy Istvan Nagy Istvan - 3 months ago 7
Javascript Question

Replace text in string between predefined characters javascript

Am am trying to replace all occurrences in a string that equals a pattern. For example:

input string:
Hi [1], my name [2] is [3].

output string:
Hi gate 1, my name gate 2 is gate 3.

[1] --> gate 1
[2] --> gate 2
[3] --> gate 3
...
[n] --> gate n


Is this possible in javascript?

Answer

Try this:

'Hi [1], my name [2] is [3]'.replace(/(\[\d+\])/g, (m, p1) => `gate ${m.match(/\d+/)[0]}`)

It returns:

Hi gate 1, my name gate 2 is gate 3