skip to Main Content

I wish to capitalize a first character of word that appears after a special character from specified set (array) is found in the string. Also I want ignore any number of spaces that it might have after the character from the array is found in the string but still capitalize the character after the special characters from the set.

Here is my code that I tried but not working:

function capitalizeChar() {
  var wordAfter = ["-", ":", "—", ".", "?", "!"];
  var c = false;
  var words = "welcome:  to the universe.";
  var charactercheck = words.split("");
  for (var i = 0; i < charactercheck.length; i++){
  if (c == true ) {
    if (charactercheck[i]!= ""){
      charactercheck[i] = charactercheck[i].toUpperCase(); 
      c=false;  }
    }
    for (var j = 0; j < wordAfter.length; j++) {
        if (charactercheck[i] == wordAfter[j]) {
        c = true; break;
        }
    }
  } 
  console.log(charactercheck.join(""));
  }
capitalizeChar();

But for some reason this code does not seem to be capitalize the ‘t’ of ‘To’ which appears after the colon ‘:’. Can someone help, please!

2

Answers


  1. Chosen as BEST ANSWER

    Here is how I solved it by using Dimava 's regex. But Alexander's solution was spot on.

    function capitalizeChar() {
      var words = "welcome:  to the universe.";
      console.log(words.replace(/([-:—.?!]s*)(w)/g, (s, a, b, c) => a + b.toUpperCase()));
    }
    capitalizeChar();


  2. Use a regular expression, should be pretty fast:

    function capitalizeChar(str, charAfter = ["-", ":", "—", ".", "?", "!"]) {
        const regex = new RegExp(`(?<=[${charAfter.join('')}]\s*)[a-z]`, 'g');
        return str.replace(regex, s => s.toUpperCase());
    }
    
    console.log(capitalizeChar('welcome:  to the universe. and -enjoy your ! suffering.'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search