Home > Web Front-end > JS Tutorial > body text

JavaScript Fun Question: String Sorting

黄舟
Release: 2017-02-13 16:16:26
Original
1978 people have browsed it

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(" ");
}
Copy after login

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

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template