some weird question with in javascript

To answer a weird question in javascript, we need to understand what the question is first. Once we have understood the question, we can use different concepts of javascript to arrive at the solution.

Here's an example of how we can manipulate a string using regex and conditionals:

Suppose the weird question is: "How to check if a given string has alternating characters?"

Here's how we can solve it using javascript:

index.tsx
function hasAlternatingChars(str) {
  let regex = /([a-z])(?!\1)/gi;
  let matches = str.match(regex);
  if (matches) {
    for (let i = 1; i < matches.length; i++) {
      if (matches[i] === matches[i-1]) {
        return false;
      }
    }
    return true;
  }
  return false;
}

console.log(hasAlternatingChars("abab")); // true
console.log(hasAlternatingChars("ababa")); // false
console.log(hasAlternatingChars("abab1")); // false
438 chars
18 lines

In the above code, we define a function hasAlternatingChars that takes a string str as input. We then define a regex pattern that matches a single lowercase letter, followed by any character which is not the same as the first letter (using negative lookahead).

We then call the match method on the input string, passing the regex as argument. This returns an array of all matches that satisfy the regex pattern. We then iterate over this array using a for loop, checking if any consecutive matches are the same. If we find a match, we immediately return false. If we reach the end and no consecutive matches are the same, we return true. If no matches are found by the regex pattern, we also return false.

We can test this function with various inputs and see if it satisfies the given weird question.

gistlibby LogSnag