Skip to content

Latest commit

 

History

History
31 lines (20 loc) · 1.06 KB

File metadata and controls

31 lines (20 loc) · 1.06 KB
标题 标签
sortCharactersInString(对字符串排序) string(字符串)

按字母顺序对字符串中的字符进行排序。

  • 使用扩展运算符 (...)、Array.prototype.sort() 和 String.prototype.localeCompare() 对 str 中的字符进行排序。
  • 使用 Array.prototype.join() 重新组合。
const sortCharactersInString = str =>
  [...str].sort((a, b) => a.localeCompare(b)).join('');

调用方式:

sortCharactersInString('cabbage'); // 'aabbceg'

应用场景

以下是一个实战示例:

结果如下:

<iframe src="codes/javascript/html/sort-characters-in-string.html"></iframe>