根据子字符串中的数字对字符串进行排序 [英] Sort a string depending on the number in the substring
问题描述
我有一个像这样的字符串is2 Thi1s T4est 3a,我需要对它进行排序,所以
数组看起来像Thi1s is2 3a T4est。 Number可以出现在字符串中的任何位置。我知道如何按字母顺序排序字符串以及如何对数字数组进行排序,但在这种情况下如何完成?有没有一种方法可以帮助它在数字上忽略字母?
我一直试图完成这项任务一段时间,任何帮助都将不胜感激!
I have a string like this "is2 Thi1s T4est 3a", I would need to sort it, so the array would look like this "Thi1s is2 3a T4est ". Number can appear anywhere in the string. I know how to sort strings alphabetically and how to sort an array of numbers, but how is it done in this case? Is there a method that helps sort it numerically ignoring letters? I have been trying to accomplish this task for a while, any help will be appreciated!
推荐答案
你可以拆分在空格和 sort
基于每个字符串中存储的数值:
You could split on spaces and sort
based on the numeric value stored in each string:
let words = "is2 Thi1s T4est 3a".split(' ');
words.sort((a, b) => a.replace(/[^\d]+/g, '') - b.replace(/[^\d]+/g, ''));
console.log(words.join(' '));
这篇关于根据子字符串中的数字对字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!