简体   繁体   中英

Determine if all letters in a string are in alphabetical order JavaScript

I'm attempting to write a JavaScript function to determine if all letters in a string are in alphabetical order. The following would keep returning "SyntaxError: Unexpected token default"

function orderedWords(str) {
    var s=str.toLowerCase().split("");
    for(var i=0; i<s.length; i++) {
        var default = s[i];
        if (s[i+1] >= default)
            default = s[i+1];
        else return false;
    }
    return true;
}

orderedWords("aaabcdefffz"); // true
orderedWords("abcdefzjjab"); // false

Any help is much appreciated.

default is a keyword in JavaScript, and cannot be a variable name.

EDIT: Also, you have a logic issue: if you iterate up to length , in your last iteration you will check the last character against undefined ; the test will fail, and you will return false . Rewrite into:

for(var i=0; i<s.length - 1; i++) {

EDIT2: I am not actually even sure why you're using that variable, since it has no bearing to the rest of your code. This should work as well (also, I moved the range from [0..length-1) to [1..length) for easier calculation):

function orderedWords(str) {
    var s=str.toLowerCase().split("");
    for(var i=1; i<s.length; i++) {
        if (s[i - 1] > s[i]) {
            return false;
        }
    }
    return true;
}

EDIT3: Simpler, shorter:

function orderedWords(str) {
    return str == str.split('').sort().join('');
}

It looks like you're looking for more than a sort? With this function you can use any letter order defined in map, and also the function removes punctuation just in case you need to check messy strings.

var map = "abcdefghijklmnopqrstuvwxyz";

function orderedWords(str,map){
    str = str.replace(/(.)(?=.*\1)/g, "");
    str = str.replace(/\W/g, '');
    var test = ""
    for(var i in map){
        if(str.indexOf(map[i])>-1){
            test += map[i];
        }
    }
    if(test.toLowerCase() == str.toLowerCase()){
        return true;
    }
    return false;
}

console.log(orderedWords("aaabcdefffz", map));
console.log(orderedWords("abcdefzjjab", map));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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