javascriptregexstringreplacecapitalize

How to capitalize the first word in each sentence using JavaScript?


This site and the internet are filled with answers to 'how to capitalize every word' but that isn't what I want to do. I couldn't find any answers anywhere to this question. Though it does seem like something that should have been answered well.

Using the previous three sentences as an example, say I had written them as:

this site and the internet are filled with answers to 'how to capitalize every word' but that isn't what I want to do. and I couldn't find any answers anywhere to this question. though it does seem like something that should have been answered well.

I'd like a JS function that will capitalize the three bolded words. Taking into account sentences can end after: '.' '?' or '!'.

I'm using Vue for this project so something that uses Vue would be great but Vanilla JS would be fine as well.


Solution

  • Since there can be several delimiters that need to be preserved, split isn't an option. The alternative easy way is to process each sentence with global replace, where a sentence ends up with punctuation marks followed by a whitespace, and punctuation mark is optional at the end of the string:

    sentences.replace(
      /.+?([.?!]+(\s+|$)|$)/g,
      sentence => sentence ? sentence[0].toUpperCase() + sentence.slice(1) : ''
    )