1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JSで文字列(数値、アルファベット混在を)並び替えたい

Posted at

JSで文字列(数値、アルファベット混在を)並び替える方法のメモです。

配列ならソートは簡単にできそうですが、文字列だと一発でできなくて、こうやるとできます。
もっとスマートな方法がありそうですが、見つかりませんでした。


let string = "1ab234";

string.split('').sort(function (a, b) {
	if (a > b) {
		return 1;
	}

	if (a < b) {
		return -1;
	}

	return 0;
}).join(',').replace(/,/g, '');

console.log(string) => "1234ab"

参考サイト
[goma
JS:配列の正しいソート方法]
(https://goma.pw/article/2015-11-18-0/)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?