javascript 文字列を反転させる
- 作成日 2021.05.09
- 更新日 2022.08.23
- javascript
- javascript

javascriptで、split(“”).reverse().join(“”)を使用して文字列を反転させるサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.101
文字列を反転させる
「split(“”).reverse().join(“”)」を使用することで、文字列を反転させることが可能です。
const str = "mebee";
const result = str.split("").reverse().join("");
console.log(result);
// eebem
以下のように、再帰的に関数を使用して変換する方法もあります。
const str = "mebee";
function reverseStr(str) {
return (str === '') ? '' : reverseStr(str.substr(1)) + str.charAt(0);
}
console.log( reverseStr(str) );
// eebem
「スプレッド構文」と「reduceRight」を使用する方法もあります。
const str = "mebee";
const result = [...str].reduceRight((x, y) => x + y);
console.log( result );
// eebem
※パフォーマンスは「「split(“”).reverse().join(“”)」」が良さそうです。
サンプルコード
以下は、
「実行」ボタンをクリックすると、フォームから取得した値を反転させて表示させる
サンプルコードとなります。
※cssには「tailwind」を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
function hoge() {
const arr = str.value.split("").reverse().join("");
result.innerHTML = arr;
// eebem
}
window.onload = () => {
// クリックイベントを登録
btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
}
</script>
<body>
<div class="container mx-auto my-56 w-56 px-4">
<div class="flex justify-center">
<p id="result" class="bg-teal-500 text-white py-2 px-4 rounded-full mb-3 mt-4">結果</p>
</div>
<div class="flex justify-center">
<input id="str" type="text"
class="shadow appearance-none border border-red-500 rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline">
</div>
<div class="flex justify-center">
<button id="btn" type="button"
class="mt-5 bg-transparent border border-red-500 hover:border-red-300 text-red-500 hover:text-red-300 font-bold py-2 px-4 rounded-full">
実行
</button>
</div>
</div>
</body>
</html>
文字列が反転されていることが確認できます。

-
前の記事
「moodle」を日本語化する 2021.05.08
-
次の記事
git コミットを指定してcloneする 2021.05.09
コメントを書く