Home > Blockchain >  Sort a string in Javascript
Sort a string in Javascript

Time:05-08

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. If the string is empty, the result will be an empty string

Example: "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?

Until now, I applied the split method to the original chain to separate them.

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

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

result

I appreciate your help

CodePudding user response:

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);

  • Related