最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to move all capital letters to the beginning of the string? - Stack Overflow

programmeradmin0浏览0评论

I've been practicing simple solutions using what I've been learning / known. The question I've faced is, how to move the capital letters in the string to the front?

I've solved it, but it's not to my expectation as my original idea was to → find the uppercase letter → put them in an array → concat the uppercase with the original string array with the uppercase letter removed in it.

Hence my question is, how can I remove the capital letter in the first conditional statement so I won't need to create another conditional statement to find the lower case and store the lower case letter in an array?

For example, the input string is 'heLLo' → output would be 'LLheo' (the capital letters are now in front).

Thank you!

function capToFront(s) {
    var sp = s.split("");
    var caps = []; 
    var lower = []
    for (var i = 0; i < sp.length; i++)
        {
            if (sp[i] == sp[i].toUpperCase()){              
                caps.push(sp[i]);
           **//How can i remove the capital letter in "sp" array as I've pushed them into the caps Array**

            }
            if (sp[i] == sp[i].toLowerCase()){
                lower.push(sp[i]);
            }
        }
    return caps.join("").concat(lower.join(""));
}

I've been practicing simple solutions using what I've been learning / known. The question I've faced is, how to move the capital letters in the string to the front?

I've solved it, but it's not to my expectation as my original idea was to → find the uppercase letter → put them in an array → concat the uppercase with the original string array with the uppercase letter removed in it.

Hence my question is, how can I remove the capital letter in the first conditional statement so I won't need to create another conditional statement to find the lower case and store the lower case letter in an array?

For example, the input string is 'heLLo' → output would be 'LLheo' (the capital letters are now in front).

Thank you!

function capToFront(s) {
    var sp = s.split("");
    var caps = []; 
    var lower = []
    for (var i = 0; i < sp.length; i++)
        {
            if (sp[i] == sp[i].toUpperCase()){              
                caps.push(sp[i]);
           **//How can i remove the capital letter in "sp" array as I've pushed them into the caps Array**

            }
            if (sp[i] == sp[i].toLowerCase()){
                lower.push(sp[i]);
            }
        }
    return caps.join("").concat(lower.join(""));
}
Share Improve this question edited Jul 19, 2020 at 10:30 Rind asked Jul 19, 2020 at 7:05 RindRind 3331 gold badge4 silver badges15 bronze badges 2
  • Providing input array and expected output array would be helpful! – Sivakumar Tadisetti Commented Jul 19, 2020 at 7:09
  • 1 Do sp.splice(i, 1) right after caps.push(s[i]). Then at the end you can just do ....concat(sp.join("")), eliminating the need for the second if. – Dev Yego Commented Jul 19, 2020 at 7:11
Add a ment  | 

4 Answers 4

Reset to default 7

With RegExp, you can acplish your goal in one line without any loops:

const result = [...'heLLo'].sort(l => /[A-Z]/.test(l) ? -1 : 0).join('');

console.log(result); // LLheo

If you want to ensure the original order among the capital letters is preserved, it will be slightly longer:

const result = [...'Hello World Foo Bar']
  .sort((a, b) => /[A-Z]/.test(a) ? /[A-Z]/.test(b) ? 0 : -1 : 0)
  .join('');

console.log(result); // HWFBello orld oo ar

You can reach your goal with a smaller loop by using Regex.

function capToFront(sp) {
    let upperRgx = /[A-Z]/g;
    let upperLetters = sp.match(upperRgx);
    for(let i=0; i < upperLetters.length;i++) {
        let indx = sp.indexOf(upperLetters[i]);
      sp = sp.substring(0,indx)+sp.substring(indx+1,sp.length);
    }
    sp = upperLetters.join("")+sp;
    
    return sp;
}

console.log(capToFront("heLLo")) // Output: LLheo

Use the Splice method to remove.

function capToFront(s) {
    var sp = s.split("");
    var caps = []; 
    var lower = []
    for (var i = 0; i < sp.length; i++)
        {
            if (sp[i] == sp[i].toUpperCase()){              
                caps.push(sp[i]);
                // Use the `splice` method to remove
                sp.splice(i, 1);
            }
            if (sp[i] == sp[i].toLowerCase()){
                lower.push(sp[i]);
            }
        }
    console.log('sp', sp);
    return caps.join("").concat(lower.join(""));
}

console.log(capToFront("stAck"))

You can also try this approach where you check the ASCII value of characters as the capital letters lie between 65 and 90 then use .sort and .join methods on the array accordingly

function capToFront(s) {
    var sp = s.split("");
    const res = sp.sort((a,b)=> isCaps(a) ? isCaps(b) ? 0 : -1 : 0)
    return res.join("")
}

function isCaps(c){
  return c.charCodeAt()>=65 && c.charCodeAt()<=90
}

console.log(capToFront('hIsAmplEStRing'))

发布评论

评论列表(0)

  1. 暂无评论