简体   繁体   English

如何对包含特殊字符和空格的字符串数组进行排序

[英]how to sort an array of string which contains special characters and white spaces

I Want to sort an array of string which contains special characters and white spaces. 我想对包含特殊字符和空格的字符串数组进行排序。 While sorting i want to ignore special characters , so that sorting of array happens based on only characters and digits. 排序时,我想忽略特殊字符,以便仅基于字符和数字对数组进行排序。

for example : array would be like: ["ibtp-17","personal (z)","personal (a)","(z)","yabcd","y(3)"] 例如:array就像: [“ ibtp-17”,“ personal(z)”,“ personal(a)”,“(z)”,“ yabcd”,“ y(3)”]

just need smart logic to implement this. 只需要智能逻辑来实现这一点。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks 谢谢


so far i have tried using replace which gives me some times correct result and some times not. 到目前为止,我已经尝试使用replace,这有时会给我正确的结果,有时却不会。

 ["ibtp-17","personal (z)","personal (a)","(z)","yabcd","y(3)"]
 .sort(function(a,b){
    return a.replace(/[^A-Z0-9]/ig, "") > b.replace(/[^A-Z0-9]/ig, "")
 }) 

Since I'm not supposed to just post code (since the OP needs to attempt something by themselves first and all that jazz). 因为我不应该只发布代码(因为OP需要首先尝试自己尝试所有事情,然后才尝试爵士乐)。 Here's some logic: 这是一些逻辑:

Array.sort() takes a comparison function. Array.sort()具有比较功能。 In said comparison function you can put some regex based special character stripper like String.replace(/[^a-zA-Z0-9 ]/g, ""); 在上述比较功能中,您可以放置​​一些基于正则表达式的特殊字符剥离器,例如String.replace(/[^a-zA-Z0-9 ]/g, ""); . and then compare the resultant strings. 然后比较结果字符串。 Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM