Home > Software engineering >  capitalize first letter of word more than 3 character Regex
capitalize first letter of word more than 3 character Regex

Time:10-12

I code something in React and i want to use Regex to capitalize first letter of word more than 3 letters with Regex, but I'am lost with Regex, i found lot of things but nothings works. Any advice?

Regex example but dont work

"^[a-z](?=[a-zA-Z'-]{3})|\b[a-zA-Z](?=[a-zA-Z'-]{3,}$)|['-][a-z]"

CodePudding user response:

Here are two example. One for sentences (like AidOnline01's answer, but using String#replaceAll) and a second one when using words only.

However, when using words only, you can also check for the length instead of using a regexp.

const sentence = "This is a sentence with a few words which should be capitialized";
const word = "capitialized";

// use String#replaceAll to replace all words in a sentence
const sentenceResult = sentence.replaceAll(/\w{4,}/g, word => word[0].toUpperCase()   word.slice(1));

// use String#replace for a single word
const wordResult = word.replace(/\w{4,}/, word => word[0].toUpperCase()   word.slice(1));

console.log(sentenceResult);
console.log(wordResult);

CodePudding user response:

\w{4,} - this regex expression will match all words that have more than 3 letters

let str = "this is Just an long string with long and short words";

const matches = str.matchAll(/\w{4,}/g);

for(match of matches) {
  str = str.substring(0, match.index)   match[0].charAt(0).toUpperCase()   match[0].slice(1)   str.substring(match.index   match[0].length);
}

console.log(str);

  • Related