admin管理员组文章数量:1426847
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 acplish this task for a while, any help will be appreciated!
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 acplish this task for a while, any help will be appreciated!
Share Improve this question edited Aug 10, 2016 at 16:57 Alex asked Aug 10, 2016 at 16:50 AlexAlex 1232 silver badges9 bronze badges 5- You'd need to write a function to parse the numbers out of each string, and then make them into their own full number. – Trasiva Commented Aug 10, 2016 at 16:52
- How is that an array of strings? I see one string. – Mulan Commented Aug 10, 2016 at 16:52
- Is there a guarantee that each string will only have one number in it? – TAGraves Commented Aug 10, 2016 at 16:52
- naomik, thanks for pointing out! I corrected that! Does it explain the issues better? – Alex Commented Aug 10, 2016 at 16:57
- TAGraves, yes, one substring will always have only one number! – Alex Commented Aug 10, 2016 at 17:00
2 Answers
Reset to default 9You 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(' '));
first define a pare function.
pare = function(x, y) {
return x.match(/\d+/g)[0] - y.match(/\d+/g)[0];
}
then use it.
var z = "is2 Thi1s T4est 3a";
z.split(" ").sort(pare).join(" ");
//"Thi1s is2 3a T4est"
Or if you prefer one line,
z.split(" ").sort(function(x, y){return x.match(/\d+/g)[0] - y.match(/\d+/g)[0];}).join(" ")
本文标签: javascriptSort a string depending on the number in the substringStack Overflow
版权声明:本文标题:javascript - Sort a string depending on the number in the substring - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745484692a2660329.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论