1

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 3

3

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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)

1 Comment

Though the rest answers are very good, I accept this because it does swap not only the (A-Z) characters.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.