Languages
[Edit]
EN

JavaScript - swap first and last character in string

0 points
Created by:
Gigadude
791

In this article, we would like to show you how to swap the first and last character in a string using JavaScript​​​​​​.

Practical example

In this example, we use the substring() method to get parts of the text and swap its first and last letters.

// ONLINE-RUNNER:browser;

let text = 'abc def';

if (text.length > 1) {
    text = text[text.length - 1] + text.substring(1, text.length - 1) + text[0];
}

console.log(text);

Output:

fbc dea

See also

  1. JavaScript - swap first and last character in every word in string

References

  1. String.prototype.substring() - JavaScript | MDN

Alternative titles

  1. JavaScript - swap first and last character in text
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join