1

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?

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    "Each line" meaning... you should be searching for newlines or breaks? Or splitting on newlines and capitalizing the first non-whitespace character of each line? Or...? Unclear. "Heavy load" to do what, capitalize words? How many lines are there?! – Dave Newton May 10 '17 at 20:17
  • 1
    Possible duplicate of [Capitalize the first letter of sentense in JavaScript/Jquery](http://stackoverflow.com/questions/31555376/capitalize-the-first-letter-of-sentense-in-javascript-jquery) – Igor May 10 '17 at 20:18
  • And assuming this is also using CSS, it's sort of a dupe of https://stackoverflow.com/questions/11129696/capitalize-first-letter-of-sentences-css – tobybot May 10 '17 at 20:31

2 Answers2

0

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.

Community
  • 1
  • 1
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
0

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)));
null_pointer
  • 1,779
  • 4
  • 19
  • 38