Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I control the font weight of any text within a paragraph (<p> tag) within braces or curly brackets { } using JavaScript

Tags:

javascript

css

I would like to be able to control the font-weight of text if bracketed inside a p tag using JavaScript.

For instance: The cow jumped over the {moon}. font-weight within {} would be increased.

This so the end user can type this into a text area and on submit the would print to page altering the font-weight within the braces or curly brackets.

Any help on this would be great.

like image 582
Leon Avatar asked Dec 19 '12 10:12

Leon


1 Answers

Here is how you can do this:

var ps = document.getElementsByTagName('p');
    foreach = Array.prototype.forEach;

foreach.call(ps, function (p) {
    var content = p.innerHTML;
    p.innerHTML = content.replace(/\{(.*?)\}|\((.*?)\)/g, function (m) {
        return '<span style="font-weight: bold;">' + m + '</span>';
    });
});
​

And of course a fiddle. For the example you need just pure JavaScript, no additional libraries.

  • Edit:

If you don't want to see the brackets in the result you can use:

var ps = document.getElementsByTagName('p');
    foreach = Array.prototype.forEach;

foreach.call(ps, function (p) {
    var content = p.innerHTML;
    p.innerHTML = content.replace(/\((.*?)\)|\{(.*?)\}/g, function (m) {
        return '<span style="font-weight: bold;">' + m.replace(/[\(\)\{\}]/g, '') + '</span>';
    });
});

Fiddle: http://jsfiddle.net/ma47D/4/

​ Best regards!

like image 81
Minko Gechev Avatar answered Sep 21 '22 22:09

Minko Gechev