Function Improvement for Capitalize

Asked

Viewed 58 times

0

This function returns me the first letter of each word in uppercase

String(str).replace(/(^|\s)\S/g, (v) => { return v.toUpperCase() })

That is, this name Roberto if turn Roberto Monteiro but this name Firecracker also becomes Roberto De Monteiro and Look at the window becomes Roberto O Monteiro, tried

String(str).replace(/(^|\s)\S{3,}/g, (v) => { return v.toUpperCase() })

and also

String(str).replace(/(^|\s){,3}\S/g, (v) => { return v.toUpperCase() })

but they return ROBERTO de MONTEIRO or ROBERTO O MONTEIRO and Roberto Oliveira or Roberto the Monk

would it be possible within this function to detect a word smaller than 3 characters and do nothing? preferably in her, without having to go to another function? or another 1-line preference function.

  • 1

    The duplicate suggested above is not 100% the same as yours, but you can easily adapt that answer for your case

  • 1

    I don’t know if you saw it but I had an answer using regex. In the comments of this reply it was concluded that regex is not the way. The code would be this String(str).replace(/\b\S(?=\S{2,})/g, (v) => {
 return v.toUpperCase() .As stated by the moderator Bacco, names such as Jorge Dos Santos, Sílvia Sa, Jó Ezequiel, hu Sung Chun, Maria Das Dores, Jet li, og Mandino will not be capitalized correctly. Thus it is not possible to calibrate the look-Ahead for each case .

  • 1

    Just one detail: {,3} actually corresponds to the characters themselves {, ,, 3 and }. If you want zero to 3 occurrences, use {0,3} - see the difference: https://repl.it/repls/WarmLimitedState - Anyway, even if it did (^|\s){0,3}, vc would be seeking from zero to 3 spaces (and not from zero to 3 letters, as you would like), and even if you could get the 3 letters, still have the problem cited in the comment above, having several short names that would be erroneously ignored.

  • 2

    @Augustovasques An alternative would be to use Lookahead negative to ignore only the prepositions "of", "of", etc: s.replace(/\b(?!d?[aeo]s?\b)(\w)(\w+)\b/gi, function(v, primeiraLetra, resto) { return primeiraLetra.toUpperCase() + resto.toLowerCase(); }) - except that it does not take the cases where everything is capitalized (e.g., "SO-AND-SO" becomes "SO-AND-SO"): https://repl.it/repls/WickedFloweryServerapplication - In the end, I think the duplicate solution looks better even to me...

  • 1

    @hkotsubo, it’s a good solution. It’s only the case of previously processing the input with toLowerCase().

  • Thanks everyone, I really could not look right for having thought about it and not being on time but helped me too much even showing me the duplicate

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.