skip to Main Content

I need to capitalize the first letter of each line inside a div
In the example below the result should be:

Lorem ipsum
Dolor sit

Amet

So each n and first letter should be replaced by n and capital letter

Please help me abut the regex part of my code

$('button').on('click', function(){
  let str = $('#wrap').text();
  let result = str.replace(/n a-z/, /n A-Z/); // how to write this?
  $('#wrap').text(result);
});
.wrap{white-space:pre-wrap;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap' id='wrap'>
lorem ipsum
dolor sit

amet
</div>
<button>CLICK</button>

2

Answers


  1. Consider the following.

    $('button').on('click', function() {
      var parts = $(".wrap").text().split("n");
      $.each(parts, function(i, line) {
        console.log("Line " + i, line);
        parts[i] = line.substr(0, 1).toUpperCase() + line.substr(1);
      });
      $(".wrap").html(parts.join("rn"));
    });
    .wrap {
      white-space: pre-wrap;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class='wrap' id='wrap'>lorem ipsum
    dolor sit
    
    amet</div>
    <button>CLICK</button>

    This assumes that your HTML or Text has End of Line characters (rn or just n).

    Login or Signup to reply.
  2. You can use ns?p{Ll}.

    1. n ( new line )
    2. s*? ( optional white spaces )
    3. p{Ll} ( any lowercase letter )

    And use the replacement function to match the first letter and replace it with its upper case with toUpperCase() function.

    $('button').on('click', function(){
      let str = $('#wrap').text();
      let result = str.replace(/ns*?p{Ll}/gu, (v) => v.toUpperCase());
      $('#wrap').text(result);
    });
    .wrap{white-space:pre-wrap;}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class='wrap' id='wrap'>
    čorem ipsum
    dolor sit
    
    amet
    </div>
    <button>CLICK</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search