EN
JavaScript - swap first and last character in string
0
points
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