Home > Mobile >  How to join the string either with a dot, exclamation mark, or a question mark?
How to join the string either with a dot, exclamation mark, or a question mark?

Time:03-23

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?

CodePudding user response:

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.

CodePudding user response:

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)

  • Related