简体   繁体   English

对 Javascript 中的字符串进行排序

[英]Sort a string in Javascript

I have a string like the following.我有一个像下面这样的字符串。 The string contains words which contain a number from 0 to 9 in them The number is the position they must have in the resulting string.该字符串包含单词,其中包含 0 到 9 之间的数字。数字是结果字符串中必须包含的 position。 If the string is empty, the result will be an empty string如果字符串为空,则结果将为空字符串

Example: "en5 4terremoto NAS1A regi2stró L0a M6arte u3n"示例:“en5 4terremoto NAS1A regi2stró L0a M6arte u3n”

Resultado:结果:

 "L0a NAS1A regi2stró u3n 4terremoto en5 M6arte"

how to go through the chain and order it, taking into account the number of each word?如何通过链对 go 进行排序,同时考虑到每个单词的个数?

Until now, I applied the split method to the original chain to separate them.直到现在,我对原始链应用split方法将它们分开。

const mensaje = 'en5 4terremoto NAS1A regi2stró L0a M6arte u3n';

const arr = mensaje.split(' ');
console.log(arr);

结果

I appreciate your help我感谢您的帮助

You could take each word, and remove all non-digits from it (with a regular expression), and use that as index in a result array:您可以获取每个单词,并从中删除所有非数字(使用正则表达式),并将其用作结果数组中的索引:

 const mensaje = "en5 4terremoto NAS1A regi2stró L0a M6arte u3n"; const result = []; for (const word of mensaje.split(" ")) { result[word.replace(/\D/g, "")] = word; } console.log(result);

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

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