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>
CodePudding user response:
You can use \n\s?\p{Ll}
.
- \n ( new line )
- \s*? ( optional white spaces )
- \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(/\n\s*?\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>
CodePudding user response:
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("\r\n"));
});
.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 (\r\n
or just \n
).