I'm coding kata from codewars that have to replace all elemements - and _ to camel case. I try to do it with regexp. In forEach function when i try to replace element with regexp have a problem because in each itearation element is the same??
var uniqueInOrder = function (str) {
const reg = /[-_]\w/g;
console.log(str.match(reg));
str.match(reg).forEach((el, i) => {
console.log(el.charAt(1));
return (str = str.replace(reg, el.charAt(1).toUpperCase()));
});
console.log(str);
};
uniqueInOrder('the_stealth_warrior');
When i log to the console el.charAt(1) its good value but when i try to replace it then always in string it always put in first element. Why is this happening?
CodePudding user response:
This is because the replace method expects a string as its first argument, but you're passing it a regular expression. Regular expressions don't have a replace method, so the regular expression itself is treated as a string.
To fix the problem, you can call the replace method with a string as the first argument and a function as the second argument. The function is called for each matching pattern in the string, taking the matching pattern found and the index position as arguments. You can then transform and return the match to replace it in the string:
let str = 'the_stealth_warrior';
const reg = /[-_]\w/g;
str = str.replace(reg, (match, index) => {
return match.charAt(1).toUpperCase();
});
console.log(str); // Output: "theStealthWarrior"
CodePudding user response:
Your code fails because the replace()
is doing all of the replacements because of the global flag.
You are reinventing the wheel because the replace()
method already supports this with a function. It will loop over each match and give you what the match is. You can then capitalize the letter.
const str = 'the_stealth_warrior';
const regEx = /[-_](\w)/g;
// _ is the matched string
// w is the capture group
const output = str.replace(regEx, (_, w) => w.toUpperCase());
console.log(output);
CodePudding user response:
You can create a method to split the string and then replace and join
const replaceAll = (string, search, replace) => {
return string.split(search).join(replace);
}
console.log(replaceAll(string, '_', '-'))
This prints the-stealth-warrior
Edit: oops just realized its missing the camelCase part
You don't need to deal with regex this way