可以javascript排序包含数字的字符串? [英] can javascript sort strings containing numbers?

查看:124
本文介绍了可以javascript排序包含数字的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个小网页应用,其中我使用了AHK和javascript。
我让AHK成为.js文件的一组图像路径类似这样

I'm making a little web-app in which I used AHK and javascript. I make AHK a group of images paths to the .js file something like this

var importedFiles = [
 "file:///F:/image1.jpg",
 "file:///F:/image10.jpg",
 "file:///F:/image11.jpg",
 "file:///F:/image2.jpg",
]

并且应该在浏览器中查看这些图像,问题是这两种语言的排序方法与windows排序方式不同。

and these images should be viewed in the browser the problem is that the sorting method of the two languages is not like the windows sorting.

我想要的是javascript对变量中的文件进行排序,以便它们像在Windows中一样被查看

What I want is javascript sort the file in the variable so that they are like they are viewed in windows like this

var importedFiles = [
 "file:///F:/image1.jpg",
 "file:///F:/image2.jpg",
 "file:///F:/image10.jpg",
 "file:///F:/image11.jpg",
]

顺便说一句:我已经搜索过之前发布的功能,但它只适用于数字,包含数字的字符串就像这种情况一样

BTW : I've searched for the functions posted before but it only works with number only and strings containing number like this case

推荐答案

var importedFiles = [
 "file:///F:/image1.jpg",
 "file:///F:/image10.jpg",
 "file:///F:/image11.jpg",
 "file:///F:/image2.jpg",
]

var customSort = function (a, b) {
    return (Number(a.match(/(\d+)/g)[0]) - Number((b.match(/(\d+)/g)[0])));

}

// use sort() and apply the customSort function
console.log(importedFiles.sort(customSort));

//outputs

[
   "file:///F:/image1.jpg", 
   "file:///F:/image2.jpg", 
   "file:///F:/image10.jpg", 
   "file:///F:/image11.jpg"
]

DEMO

DEMO

这篇关于可以javascript排序包含数字的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆