let string = 'abcdefghij'; the result I want string = 'abdcefhgij'. The changes should be made are cd to dc and gh to hg rest of the string is unaltered.
Asked
Active
Viewed 221 times
-1
-
Use regex replace. – Michal Miky Jankovský Apr 02 '21 at 08:29
-
Does this answer your question? [Javascript swap characters in string](https://stackoverflow.com/questions/48571430/javascript-swap-characters-in-string) – Ivica Pesovski Apr 02 '21 at 09:20
-
Thank you Mr. Michal, could you please write it for me ? – PVD Apr 02 '21 at 23:42
-
@IvicaPesovski It worked, but how to shortened that ? – PVD Apr 03 '21 at 01:54
2 Answers
0
const string1 = 'abcdefghij'.replace(/[cd]/g, (c) => (c == 'c' ? 'd' : 'c'));
console.log(string1);
const string2 = string1.replace(/[gh]/g, (c) => (c == 'g' ? 'h' : 'g'));
console.log(string2);
I did this. finally got the result in the form of string2. Anyone could suggest how to do it in one go?

PVD
- 27
- 8
0
To do it in one go, create a function that will map each characters you want to swap, like this:
function charReplace(char) {
if(char == 'c') return 'd';
if(char == 'd') return 'c';
if(char == 'g') return 'h';
if(char == 'h') return 'g';
}
Then you can pass this function as the second parameter to the replace
function like this:
const originalString = 'abcdefghij';
const replacedString = originalString.replace(/[cdgh]/g, ($1) => charReplace($1));
If you need to map more chars, just add if
blocks in the charReplace
function. If it gets too long, you can implement it by keeping the map into an array and returning the element at the correct index.

Ivica Pesovski
- 827
- 7
- 29