Trouble with Javascript easy coderbyte challenge

1.6k Views Asked by At

I'm attempting to answer this question:

Using the JavaScript language, have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.

Here's my solution:

function SimpleSymbols(str) { 
var test;

  for (var i =0; i<str.length; i++){

    if ((str.charAt(i)!== '+' && str.charAt(i+1) === str.match(/[a-z]/))
    ||(str.charAt(i+1) === str.match(/[a-z]/) && str.charAt(i+2) !== '+')){
    test = false;
    break;
    }  

    else if (str.charAt(0) === str.match(/[a-z]/)){
         test = false;
         break;}

     else {
      test= true;}


  } 
  return test; 

};
1

There are 1 best solutions below

0
On

I think you can just use two regex and then compare the length of arrays returned by them

function SimpleSymbols(str){
   return str.match(/[a-z]/g).length == str.match(/\+[a-z]\+/g).length;
}

The first regex /[a-z]/g will match all the letters and /\+[a-z]\+/g will match all the letters which are followed and preceded by a literal +.

Then, we just use the Array.length property to check if the lengths are same or not and then return the Boolean result. As simple as that.