DEV Community

Cover image for Using the string.replace method in Javascript
Oluwajuwon
Oluwajuwon

Posted on

Using the string.replace method in Javascript

Earlier today I was working on a challenge on Codewars or as they're popularly called; Kata. While working on it I also did some research on how I could go about solving it, and I stumbled on a string method I had never used before. The replace() method.

String.prototype.replace()

According to MDN, the replace method returns a new string after all or part of it has been replaced based on a replacement pattern/string.
The pattern could be a substring or a regular expression (I'm guessing you all know about regular expressions, if you don't you can check this out).

The replace method takes in two arguments: 

  1. The pattern or substring to be matched.
  2. The new String/Substring or a function that returns a new string, to replace the matched string.

Let's have a look at the replace syntax


const newString = string.replace(substring/pattern, newstring/function)

Solving the challenge

The challenge to Convert string to camel case - Codewars

What we want to do is find all the characters in the given string that match either the underscore( _ ) or the hyphen (-) and the alphabets after them, transform them to uppercase letters and remove the non-alphabetic characters.

First of all, since the replace method can take a regular expression to be used for matching, we can create an expression that matches what we want to replace.

const regExp = /[^a-z][a-z]/gi

Let's break down the regular expression above

[^a-z] - this matches any character in the string that is not an alphabet from a-z

[a-z] - this matches any character in the string that is an alphabet from a-z

g - global, to make sure it checks the whole string

i - insensitive, to make sure it doesn't bother about the case of the string

Now that we've found how to match the string/characters we want to work on, we should also figure out how to replace them in the string.

Let's create a function as the second parameter that can take the matched characters in the string and convert them to the new characters we want.


const newWord = word => word.toUpperCase().replace(/[^a-z]/gi, '')

Breakdown of the function above

word.toUpperCase() - this transforms the matched characters to uppercase

replace(/[^a-z]/gi, '') - this replaces the transformed characters that aren't alphabets from a-z with empty strings

The full method for the solution

const toCamelCase = str => {
  return newWord = str.replace(/[^a-z][a-z]/gi, word => word.toUpperCase().replace(/[^a-z]/gi, ''))
}

I'm sure there are several ways to have solved this particular problem, but using the replace method seems very straightforward and easy to use.
You can also comment with your own solutions or questions.

I hope this helps someone out…

You can also reach me on Twitter ✌️

Top comments (0)