Your task is to sort a given string.
Each word in the string contains a separate number, which represents the position of the word in the string. The number
is between 1 and 9, so the word containing 1 will be the first word.
If the given string is empty, return an empty string.
For example: "is2 Thi1s T4est 3a"
Return: "Thi1s is2 3a T4est"
Okay, what? Let’s see how to write such a function.
1. First split the given string according to spaces. After all, arrays are easier to operate than strings.
2. Then formulate sorting rules. Which word contains a larger number will be ranked lower.
3. Then, use the sort method of the array to pass in the sorting rule anonymous function to perform customized sorting.
4. Finally, aggregate the array after sort and return a string.
This question is quite easy, and skilled students can solve it quickly.
function findNumber(str){ for(var i=0;i<str.length;i++){ var chr = str.charAt(i); if(!isNaN(chr)){ return parseInt(chr); } } } function order(words){ return words.split(" ").sort(function(a,b){ return findNumber(a) - findNumber(b); }).join(" "); }
The above is the content of JavaScript interesting questions: string sorting. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!