How can i eliminate white spaces in my regex code?

Viewed 54

I'm trying to use Regex with my assignment.

2 problems here I can't solve:

problem 1: The 1st if the statement is meant to put the string into "pascal" case. The 2nd if statement into "camel" case. Regardless the statement it looks like executions stops after 1st statement. What do I do wrong here?

problem 2: My 1st if statement even though return result ("pascal") i can not figure out how to get rid of white spaces in my regex part of the code.

Please help. stuck 2nd day in a row.

const makeCase = function(input, type) {
  //place your code here
  
    let inType = type;
    let finalInput = (type === inType)
  
  
    if(finalInput) {
      return input.replace(/^(.)|\s+(.)/g, function(str){
        return str.toUpperCase();
      });
    } else if(finalInput) {
      return input.replace(/\W+(.)/g, function(str){
        return str.toUpperCase();
      });
    } 
  };

  console.log(makeCase("this is a string", "pascal"));  
  console.log(makeCase("this is a string", "camel"));


4 Answers

Perhaps do ucwords, then remove the spaces and then based on type, either upper or lower case first char.

function makeCase(str, type) {
  str = (str + '').replace(/^([a-z])|\s+([a-z])/g, $1 => $1.toUpperCase()).replace(/ /g, '')
  return str.charAt(0)[type === 'pascal' ? 'toUpperCase' : 'toLowerCase']() + str.slice(1)
}

console.log(makeCase("this is a string", "pascal")); // ThisIsAString
console.log(makeCase("this is a string", "camel"));  // thisIsAString

Rationale

The String.replace method only performs one replacement.

In the browser you can do String.replaceAll, however in node you can not.

I found that the simplest way to solve this is to split up the string where there is a space using split, and glue the words together without a space using join.

As one function

Here's a working example of how I would write it;

const makeCase = function(input, type) {
  //place your code here
  return input
    .split(' ')
    .map((word, index) => {
      if (index === 0 && type === 'camel') {
        return word
      } else {
        const [first, ...rest] = word;
        return `${first.toUpperCase()}${rest.join('')}`;
      }
    })
    .join('');
  }


console.log(makeCase("this is a string", "pascal"));
console.log(makeCase("this is a string", "camel"));

Creating replaceAll()

Creating your own replaceAll function could look like this.

export const replaceAll = (input, searchValue, replaceValue) => {
  return input.split(searchValue).join(replaceValue);
};

Note that string.split separator parameter can also make use of Regex.

Now you

Recommend trying to understand each part and writing your own variation.

This is wrong as finalInput will always be true:

    let inType = type;
    let finalInput = (type === inType)

One problem: put a flag i with g. It helps to ignore case.

Related