check to see if string matches requirements

The function generateHashtag(str); is passed a string that must meet the following criteria:

  • If the final result is longer than 140 chars it must return false.
  • If the input is a empty string it must return false.
  • It must start with a hashtag (#).
  • All words must have their first letter capitalized.
  • Example Input to Output:

    " Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata"

    " Hello World " => "#HelloWorld"

    Here is my code so far:

    function generateHashtag (str) {
        if (!str) {
            return false;
        } else {
            var los = str.toLowerCase();
            var res = los.replace(/b./g, function(m){ return m.toUpperCase(); });
        } 
    
        if ( res.charAt( 0 ) != '#' ) { 
            res = "# " + res;
        } else {
            res = "" + res;
        }
    
        if (res.length > 140) {
            return false; 
        } else {
            return res;
        }
    }
    

    This is a coding challenge from the codewar.com site. I get the following message there Test didn't pass: Unknown error . It works on js fiddle link to js fiddle


    Does this work?

    function generateHashtag (str) {
      if(!str || str.length == 0 || (str.replace(/([^a-zA-Zs])/g, "").length + 1) > 140)
        return false;
    
      var finalString = "";
      str = str.replace(/([^a-zA-Zs])/g, "").trim().toLowerCase().split(" ");
    
      for(i in str)
        finalString += str[i].charAt(0).toUpperCase() + str[i].slice(1);
    
      return "#" + finalString;
    }
    

    https://jsfiddle.net/c0m6bcq6/1/

    链接地址: http://www.djcxy.com/p/2882.html

    上一篇: 在Node.js中,我如何从其他文件“包含”功能?

    下一篇: 检查字符串是否符合要求