tarik
tarik

Reputation: 31

How to swap character positions in a string JavaScript

I'm making a deciphering function and I'm stuck on a part where I need to swap the positions of the second letter and the last letter of the string. I have also tried using the replace method but I think substring should be used.

Hello should equal Holle, etc

function decipher(str) {
  let s = ""
  for (let word of str.split(" ")){
    let dig = word.match(/\d+/)[0]
    word = word.replace(dig, String.fromCharCode(dig))
    let secondLetter = word[1]
    let lastLetter = word[word.length - 1]
    let swapped = word.substring(0,1) + lastLetter + word.substring(2,3) + secondLetter
    s += swapped + " "
  }
  return s
}; 

Upvotes: 2

Views: 2831

Answers (6)

arp
arp

Reputation: 371

You can achieve it by splitting it

function swapCharacters(str,i,j){
  str=str.split("")
  [str[i],str[j]]=[str[j],str[i]]
  return str.join("")
}

Looks clean :)

Upvotes: 0

Mikias
Mikias

Reputation: 141

We can create a basic function like this

const swapCharacters = (str, char1, char2)=>{
  let a = str.replaceAll(char1, '~')
  let b = a.replaceAll(char2, char1)
  let c = b.replaceAll('~', char2)
  return c
}

console.log(swapCharacters('42,23.5453,6', '.', ',')) //42.23,5453.6

Upvotes: 0

customcommander
customcommander

Reputation: 18901

You can destructure the string:

const swap = ([a, b, ...xs]) => [a, xs.pop(), ...xs, b].join('');
//                                  ^^^^^^^^         ^
//                                  |____swapping____|

swap("Hello");
//=> "Holle"

With destructuring you will also support things like emojis (but maybe not graphemes):

swap("H🌯ll🍣");
//=> "H🍣ll🌯"

Swapping words in a string:

const decipher = str => str.split(' ').map(swap).join(' ');

decipher("Hello World");
//=> "Holle Wdrlo"

decipher(decipher("Hello World"));
//=> "Hello World"

Why destructure?

Reading characters in a string via index or (simple) regex probably won't work with multi-codepoint characters such as (but not limited to) emojis:

"🌯".length;
//=> 2! Not 1.

"🌯".charAt(0);
//=> "\ud83c"! Not "🌯".

Consider this swap function:

function swap(str) {
  var arr = str.split('');
  var [a, b] = [arr[1], arr[arr.length-1]];
  arr[1] = b;
  arr[arr.length-1] = a;
  return arr.join('');
}

Works fine with plain old ASCII:

swap("Hello");
//=> "Holle"

Doesn't work as you would expect with emojis:

swap("H🌯ll🍣");
//=> "H\udf63\udf2fll\ud83c\ud83c"

Upvotes: 1

Nikhil Patil
Nikhil Patil

Reputation: 2540

If it is only for a specific use case (i.e. swap second and last), you can do it with simple regex -

Regex -(.)(.)(.*)(.)

const str = "Hello";
console.log(swap(str));

function swap() {
  return str.replace(/(.)(.)(.*)(.)/, "$1$4$3$2")
}

Upvotes: 0

Kamen Kotsev
Kamen Kotsev

Reputation: 303

Consider extracting it into a function to keep a cleaner codebase:

function swapSecondAndLastLetter(str) {
   // Split the string into a mutable array
   let original = str.split('');

   original[1] = str[str.length-1];
   original[original.length-1] = str[1];

   // Join the mutable array back into a string
   return original.join('');
}

Upvotes: 0

Rinkal Rohara
Rinkal Rohara

Reputation: 352

Please change this line:

let swapped = word.substring(0,1) + lastLetter + word.substring(2,word.length - 1) + secondLetter;

Upvotes: 1

Related Questions