[JS Practice] Adjacent pairs in a string

Title :

Adjacent pairs in a string


Supplied with a single string, return the number of all adjacent pairs in that string.

The words within the string are separated by whitespace.

The function should be case-insensitive (i.e., the input string “orange OrAnGe” is a match).

Some example input/output:

//returns 0

// returns 1
countAdjacentPairs('cat dog dog') 

// returns 1 (The first pair has been matched, and will be ignored from then on).
countAdjacentPairs('dog dog dog') 

// returns 2
countAdjacentPairs('cat cat dog dog cat')

My solution :

function countAdjacentPairs(searchString) {
  if(searchString.trim() == '') {  // Check empty string
    return 0;

  var arrString = searchString.toLowerCase().split(' '); // Put string into array
  var len = arrString.length;  // Get the size of array
  var counter = 0;

  for(var i=0; i<len; i++) {
    if(typeof arrString[i+1] != 'undefined') { // Check if the next element not exist
      if(arrString[i] == arrString[i+1]) { // Check adjacent elements
  return counter;

Here is a solution more cooool :

function countAdjacentPairs(searchString) {
  var result = searchString.match(/(\b\w+)\s\1/ig);
  return result == null ? 0 : result.length;

Ref. from codewars


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s