user2911849
user2911849

Reputation: 93

Capitalize first letter of each line using JavaScript

I'd like to know how I could capitalize the first letter of a row in JavaScript like in this PHP code :

<?php

$textParts = explode("\n", $text);
foreach ($textParts as $key => $value) {
   $textParts[$key] = ucfirst($value);
}

$text = implode("\n", $textParts);

$text="namjaga da geureochi mwo narago dareugetni
ni mameul da gajyeodo naragabeorigo maneun
namjaga da geureochi mwo"

?>

<p>
<?php echo $text; ?>
</p>

In JS, I get the text into the "Roman" DIV after a tranformation :

<div id="Roman"> </div>

<script>

<?php include("../../tools/js/romantool.js"); ?>
function affichar() {
  document.getElementById('Roman').innerHTML = latin_to_roman(
    document.getElementById('Parol').innerHTML
  );
}
affichar();

</script>

Does anyone know how I should proceed to do as in the previous PHP example ? Thank you !

Upvotes: 0

Views: 700

Answers (4)

Orlov Igor
Orlov Igor

Reputation: 1

String.prototype.capitalize = function () {
    var sa = this.replace(/-/g, ' ');
    var saa = sa.toLowerCase();
    var sb = saa.replace(/(^|\s)([a-z])/g, function (m, p1, p2) {
        return p1 + p2.toUpperCase();
    });
    var sc = sb.replace(/\s+/g, ' ');
    return sc;
};

Use like

'String'.capitalize();

Upvotes: 0

Master Slave
Master Slave

Reputation: 28529

In fact I would go right in between the two suggested answers so far. I would use javascript to replace the line breaks with a tag that will add structure around text e.g.

var str = document.getElementById('Parol').innerHTML;
str = '<span>' + str.replace(/(?:\r\n|\r|\n)/g, '</span><span>') + '<span>';
document.getElementById('Roman').innerHTML = str;

And than style it in whichever way you want using CSS, your case would be

   span {
        display: block;
    }

    span:first-letter {
        text-transform: uppercase;
    }

Here's a fiddle

http://jsfiddle.net/58qkwezk/1/

Adding structure to your text will help you manipulate it much easier

Upvotes: 1

dave
dave

Reputation: 64657

You could split the text on newlines, map the array so each line gets an uppercase first letter, then join with newlines:

text = text.split("\n").map(function(line) { 
           line = line[0].toUpperCase() + line.substr(1); 
           return line;
}).join("\n");

For example:

Console.log showing example

Upvotes: 2

Prashant G
Prashant G

Reputation: 4900

If you are trying just to display on the webpage.

How about this :

<style>
p.uppercase {
    text-transform: capitalize;
}
</style>
<p>this is a paragraph</p>

If you want to use JS:

$("p").css({"text-transform":"capitalize"});

Will output:

This Is A Paragraph.

Upvotes: 1

Related Questions