Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

412
Views
How to join the string either with a dot, exclamation mark, or a question mark?

I want to convert a string to the sentence case. That is, uppercase the first character in each sentence and lowercase the following characters. I managed to do this. However, after splitting the string and converting it to a sentence case, I need to join it again with a corresponding character.

Here is my code that splits the string into sentences:

const string = "my seNTencE . My sentence! my another sentence. yEt another senTence?   Again my sentence   .";

function splitString(str) {
    str = str.split(/[.!?]/);
    
    for(let i = 0; i < str.length; i++) {
        str[i] = str[i].trim();
    }
    
    for(let i = 0; i < str.length; i++) {
        str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1).toLowerCase();
    }
    
    return str;
}

console.log(splitString(string));

In the return statement, I want to return joined strings. For example, the first sentence must end with a dot, and the second must end with an exclamation mark, etc. How to implement this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

str.split eliminates the result of the regex match from the string. If you want to keep it, you can place the separator in a lookbehind like this:

str.split(/(?<=[.!?])/);

The syntax (?<= ) means the regex will find positions that are preceded by punctuation, but won't include said punctuation in the match, so the split method will leave it in.

As a side note, keep in mind that this function will ruin acronyms, proper nouns, and the word I. Forcing the first letter after a period to be a capital letter is probably fine, but you will find that this function does more harm than good.

about 4 years ago · Juan Pablo Isaza Report

0

Use a regular expression with capture groups. This regex uses the lazy ? modifier so the match will end at the first [!.?], and the global g flag to grab all matches.

const string = "my seNTencE . My sentence! my another sentence. yEt another senTence?   Again my sentence   ."

const rx = /(.*?)([.!?])/g

const found = []
while (m = rx.exec(string)) {
  let str = m[1].trim()
  str = str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
  found.push(str + m[2])
}

console.log(found)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!