Programming Questions

  • Newest
  • Popular Tags
  • Ask Question
  • String Object to String
    Why does the following code return "YEAhH" when str="yeaHH". This will help me understand the "for in" loop a bit better.
    function SwapCase(str) { 
      var pattern = /[A-Z]/g
      var x = new String();
      var result = "";
    
      for(var i = 0; i<str.length; i++){
        if(pattern.test(str.charAt(i)) != true){
          x[i] = str.charAt(i).toUpperCase();
        }else{
          x[i] = str.charAt(i).toLowerCase();  
        }
        }
      for(val in x){
        result += x[val] + ' ';
      }
      return result;     
    
    } 
    
    // keep this function call here 
    // to see how to enter arguments in JavaScript scroll down
    SwapCase(readline());
    
    JackC27 posted this question on 9/30/14 | javascript, string, object
    Answers
  • +
  • 2
  • -
  • Removing g from your Regex expression seems to solve the problem, I'm not sure why.
  • +
  • 0
  • -
  • As @mattlarsh has answered, removing the "g" should make it work. However, I would attribute this awkward behaviour to how RegExp work. Im not quite enlightened in the subject but this resource <em>might</em> prove helpful: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
  • +
  • 0
  • -
  • First off you are using short hand to create your pattern. The correct / proper syntax is this
    var pattern = new RegExp(/[A-Z]/g);
    
    Also .charAt is unesescary, strings by default double as arrays so you can use this instead
    
    if (!pattern.test(str[i]) {
      //code here
    }
    
    Also why construct a string object then the result, why not both at the same time.  The code would look like this
    
    var pattern = new RegExp(/[A-Z]/g);
    var result="";
    
    for (var i=0;i<str.length;i++) {
        if (pattern.test(str[i]) {
            result+=str[i].toLowerCase()
        } else {
            result+=str[i].toUpperCase()
        }
    }
    
    return result;
    This was coding on the move without testing so hopefully it works.
  • +
  • 0
  • -
  • An update: I have tried a few different ways to get this done. All of them yeild the same akward behavior. This means it's not anything to do with the "for in" loop like I thought it might be and might have more to do with Regex or the way my for loops are constructed.
  • +
  • -1
  • -
  • This question appears a lot it interviews. It can be seen here: www.algrim.co/posts/89-70-javascript-interview-questions-to-hire-or-get-hired
  • +
  • -1
  • -
  • Log in to write an answer.