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.
In this example, we use the substring()
method to get parts of the text and swap its first and last letters.
xxxxxxxxxx
1
let text = 'abc def';
2
3
if (text.length > 1) {
4
text = text[text.length - 1] + text.substring(1, text.length - 1) + text[0];
5
}
6
7
console.log(text);
Output:
xxxxxxxxxx
1
fbc dea