Targeting specific text entered into form input field and add styles to it?

How can I style the 2nd word entered into a form input text field? Not in the field itself where they are entering the text, but once the person entering the text hits the "enter" button and the data gets output.

The same arrangement of text always gets entered into this field. It's 3 numbers, then a space, then a name.

If I input "903 Houston" into the form input field and run it how can I make the style of the second word entered "Houston" (lets say make it bold) and make it output "903 Houston" Assuming I need to inject HTML tags somehow to just the second word entered? How can this be accomplished?

Answers 1

  • Given a string of words, I think the easiest way to style individual words is to .split() the input string into an array of individual words and then update whichever one(s) you wanted to based on their position in the array, before .join()ing back together into a string of HTML. In that way it is easy enough to wrap an individual word in a span element with a specific class, and then style that class however you like.

    "The text is entered by a site administrator and gets output to the front of the site on a page. There must be a way this can be targeted and styled."

    Yes. Select the element in question with jQuery and then apply the above technique to it. Perhaps a little something like this:

    $(".styleMe").html(function(i, currentText) {
        var words = currentText.split(" ");
        words[1] = "<span class='bold'>" + words[1] + "</span>";
        words[3] = "<span class='highlight'>" + words[3] + "</span>";
        return words.join(" ");
    .bold { font-weight: bold; }
    .highlight { background-color: blue; color: white; }
    <script src=""></script>
    <p>Some text.</p>
    <p class="styleMe">These are some words to be styled.</p>
    <p>Some other text.</p>

    Note: if there is a possibility the input format may vary in length then obviously you should test that, so that, e.g., you're not trying to update the second word in a string that only has one word in it.

Related Articles