swap two characters in a string javascript

Viewed 121

I have a string 2A some text 2B 2C some text 2D and I want to swap 2 with its' next character.

The result will be A2 some text B2 C2 some text D2.

How can I achieve it?

I tried as below but it doesn't work.

const str = '2A some text 2B 2C some text 2D';
const strArray = str.split("");
const result = str.replace(/2/gm,(match,index)=>{
     return strArray[index+1]+match;
})
document.write(result)

3 Answers

Using regex capture group

Regex Demo

https://regex101.com/r/k5UXf7/1

const str = '2A some text 2B 2C some text 2D';

const result = str.replace(/(2)([A-Z])\b/g, '$2$1')

document.write(result)

OR

const str = '2A some text 2B 2C some text 2D';

const result = str.replace(/(2)([A-Z])\b/g, (match, p1, p2) => p2 + p1)

document.write(result)

Here's a simple way to achieve the result using Regex

const str = '2A some text 2B 2C some text 2D';
const result = str.replace(/2(.)/gm, "$1" + "2")
document.write(result)

Limited solution:

const s = '2A some text 2B 2C some text 2D';

(function(s) {
  let swapped = [...s]
  for (let i = swapped.length; i--;) {
    if (swapped[i] === "2") {
      swapped[i] = swapped[i + 1]
      swapped[i + 1] = "2"
    }
  }
  console.log(swapped.join(''))
})(s);

Related