I need to understand this part of the code
let x = "hello my name is chrono"
const finalSentence = x.replace(/\S\w | \s\w/g, letter => letter.toUpperCase());
>>>>>>>>>>>>> I need to understand this part of the code >>>>>>>>>>>> letter => letter.toUpperCase()
Is it like writing this
function letter(letter) {
letter.toUpperCase()
return letter
}
12 Replies
Exactly, yes
It's called an arrow function. Give me a sec to find the MDN link
Arrow function expressions - JavaScript | MDN
An arrow function expression is a compact alternative to a traditional
function expression,
but is limited and can't be used in all situations.
but I want to know for that part of the code, could you write an outside function and pass it into that part of the code
like
const finalSentence = x.replace(/(^\w{1})|(\s+\w{1})/g, letter());
function letter(letter) {
letter.toUpperCase()
return letter
}
Yes, you can do that as well
But, instead of invoking the function like in your question, you just provide the reference to that function:
but its still giving me an error
did I write the function correctly
and the error is?
always read the errors, we can't really do anything without this information
o forgot the closing bracket
but not the output is
“helundefinedundefinednaundefinedundefinedchrono”
And what do you think may cause that
What is the expected output vs the actual output?
i think its the function
there isn’t any parameter in the function right>
?
"Hello My Name Is Chrono"
The issue is not the function, it's the pattern.
Read the description on how replace works when you provide a function and you will see the problem: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement
Hint: in the output you are seeing a bunch of "undefined" in between the text
when you say pattern do you mean the REGEXP
/(^\w{1})|(\s+\w{1})/g
thats what I was using
\b
word boundary
\w
any word character
/g
global, all matched
(m)=> ...
for each match
So every first word character after a word boundary will be matched and replaced
or if you want the replacement outside the replace function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceString.prototype.replace() - JavaScript | MDN
The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced. The original string is left unchanged.