

Convert string to camel case CodeWars Kata
source link: https://dev.to/farhaduneci/convert-string-to-camel-case-codewars-kata-299i
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Codewars
Codewars is a platform that helps you learn, train, and improve your coding skills by solving programming tasks of many types and difficulty levels. Here is the first Kata I've solved here, and I would like to share my solutions here in DEV.
What is a Kata?
On Codewars, kata are code challenges focused on improving skill and technique.
❓ Here is my first Kata:
Write a method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
Examples
"the-stealth-warrior" gets converted to "theStealthWarrior"
"The_Stealth_Warrior" gets converted to "TheStealthWarrior"
💡 We can use Regex to perform a search and replace in almost all programming languages.
A regular expression is a sequence of characters that specifies a search pattern. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation. It is a technique developed in theoretical computer science and formal language theory.
I used preg_replace_callback
function in PHP which performs a regular expression search and replace using a callback to find "_\w"
or "-\w"
patters like _a
or -b
and replace them with the equivalent uppercase character. like _b
=> B
so the-stealth
will be theStealth
.
💻 So, my solution in PHP is:
function toCamelCase($str){
return preg_replace_callback('/(\-|\_)([a-z])/i', function ($match) {
return strtoupper($match[2]);
}, $str);
}
You might ask what is that $match[2]
, well here is the var_dump($match)
output:
array(3) {
[0]=>
string(2) "_s"
[1]=>
string(1) "_"
[2]=>
string(1) "s"
}
as you see inside of each iteration this array contains, the matched string beside regex groups! in our case here "$2" = $match[2]
.
Thank You ❤️
I wish my posts to be useful to anyone who's new to the world of programming or anybody who's curious 🧐!
If you find the content useful to you, please comment your thoughts, I would love to learn from you all.
Thank you for loving directions.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK