[英]Sort complex string in javascript
I have an input string like, CF10, CF6_S01, CF11_S01
. 我有一个输入字符串,例如
CF10, CF6_S01, CF11_S01
。 I want to sort this in ascending order like, CF6, CF10, CF11
. 我想按升序将其排序,例如
CF6, CF10, CF11
。 Not concern about _S01
in string. 不关心字符串中的
_S01
。 I am trying to split based on first number after alphabets but didn't work. 我正在尝试根据字母后面的第一个数字进行拆分,但是没有用。
var reA = /[^a-zA-Z]/g; var reN = /[^0-9]/g; return function(a, b) { var aA = a[key].replace(reA, ""); var bA = b[key].replace(reA, ""); if (aA === bA) { var aN = parseInt(a[key].replace(reN, ""), 10); var bN = parseInt(b[key].replace(reN, ""), 10); return aN === bN ? 0 : aN > bN ? 1 : -1; } else { return aA > bA ? 1 : -1; } };
Can someone help me how I can produce output: CF6, CF10, CF11
using regular expression in javascript? 有人可以帮我如何生成输出:
CF6, CF10, CF11
使用JavaScript中的正则表达式吗?
You could try this simple one-liner solution: 您可以尝试以下简单的单线解决方案:
var arr = ['CF10', 'CF6_S01', 'CF11_S01'] console.log(arr.sort((a,b) => (a.match(/\\d+/)[0] - b.match(/\\d+/)[0]))) // if you don't want _S01 part console.log(arr.sort((a,b) => (a.match(/\\d+/)[0] - b.match(/\\d+/)[0])).map(e => e.split('_')[0]))
A simple version specific for your use case without the use of a regular expression: 一个针对您的用例的简单版本,不使用正则表达式:
'CF10, CF6_S01, CF11_S01'
.split(',')
.map(x => x.trim())
.sort((a, b) => {
const [aa] = a.split('_')
const [bb] = b.split('_')
return aa.slice(2) - bb.slice(2)
})
You could separate the first part into not number characters and the number. 您可以将第一部分分为非数字字符和数字。 Then sort by first part and second.
然后按第一部分和第二部分进行排序。
function getParts(s) { return s.match(/^(\\D+)(\\d+)/).slice(1); } var array = ['CF10', 'CF6_S01', 'CF11_S01']; array.sort((a, b) => { var aa = getParts(a), bb = getParts(b); return aa[0].localeCompare(bb[0]) || aa[1] - bb[1]; }); console.log(array);
For soting just by the first number, you could omit other characters. 如果只按第一个数字输入,则可以省略其他字符。
function getValue(s) { return s.match(/\\d+/); // returns an array with only one element } var array = ['CF10', 'CF6_S01', 'CF11_S01']; array.sort((a, b) => getValue(a) - getValue(b)); console.log(array);
This is not a solution using regex
这不是使用
regex
的解决方案
let arr = ['CF10', 'CF6_S01', 'CF11_S01']; arr.sort((a,b) => { let var1 = a.split('_')[0].split('CF')[1]; let var2 = b.split('_')[0].split('CF')[1]; return var1 - var2 }) console.log(arr)
You can simply use split
function to extract the numeric part and perform sorting based on it 您可以简单地使用
split
函数来提取数字部分并基于它进行排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.