简体   繁体   中英

Capitalize first word of each line

I am trying to capitalize the first word of each line using jquery.

I have tried the following script:

sentence =  sentence.charAt(0).toUpperCase() + sentence.slice(1);

This works fine for the first line, but the rest of the lines are not capitalized. I want the next line's first letter also to be capitalized. This process should continue for the next lines as well.

I think adding the long sentences might work, but I'm afraid if it will put a heavy load on the system. If so, is there any other simple method that can solve this issue?

As said before in comments, you need to specify what is new line in your text. Just a new line ( \\n ) ? Here's an example working only with new lines characters:

 var text = document.getElementById("pre").innerText, newText = text .split(/\\n/g) .map(x => x.charAt(0).toUpperCase() + x.substr(1)) .join("\\n"); console.log(newText); 
 <pre id="pre"> lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ut leo mauris. integer pharetra imperdiet mauris a tempor. cras facilisis pulvinar porta. cras viverra pellentesque dui, ut pulvinar ex commodo eu. curabitur sodales vitae velit ut luctus. aliquam diam justo, facilisis vitae facilisis nec, commodo ut nunc. duis bibendum, sem laoreet mollis laoreet, ipsum velit pulvinar magna, quis accumsan leo felis id lorem. proin et suscipit dui. duis porttitor nibh non faucibus pretium. </pre> 

Capitalize function taken from here . Note that 3rd and 6th lines haves more than one sentence, but they won't be treated as they are not in new lines.

Here is one solution using normal javascript :

let sentence = 'this is a new sentence.';

console.log(sentence.split(' ', 1)[0]
                    .charAt(0)
                    .toUpperCase()
                    .concat(sentence.substring(1)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM