vince
vince

Reputation: 172

How to Wrap first and second word in two italic with jQuery

This is my code:

jQuery('.n2-ss-item-content').each(function(){
    var me = jQuery(this);
    me.html(me.html().replace(/^(\w+)/, '<i>$1</i>'));
});

The HTML output is showing this:

<i>Majesty</i> Purple | 24” w x 20” h | SOLD

Suppose to be it should be like this:

<i>Majesty Purple</i> | 24” w x 20” h | SOLD

Upvotes: 2

Views: 60

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

jQuery('.n2-ss-1item1').each(function(){
    var me = jQuery(this);
    me.html(me.html().replace(/^([^|]+)/, '<i>$1</i>'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="n2-ss-1item1">Majesty Purple | 24” w x 20” h | SOLD</p>

<p class="n2-ss-1item1">Majesty Blue | 24” w x 20” h | SOLD</p>

Upvotes: 2

Pranav C Balan
Pranav C Balan

Reputation: 115282

You need to include whitespace with the regex along with the word characters or use negated character class to avoid |, like ^([^|]+). In addition to that, you can use html() with a callback(the second argument is old HTML content) and which iterates internally and updated content with the returned value.

jQuery('.n2-ss-item-content').html(function(_, html){
    return html.replace(/^([\w ]+)/, '<i>$1</i>');
});

or

jQuery('.n2-ss-item-content').html(function(_, html){
    return html.replace(/^([^|]+)/, '<i>$1</i>');
});

jQuery('.n2-ss-item-content').html(function(_, html) {
  return html.replace(/^([\w ]+)/, '<i>$1</i>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="n2-ss-item-content">Majesty Purple | 24” w x 20” h | SOLD</p>
<p class="n2-ss-item-content">Majesty Blue | 24” w x 20” h | SOLD</p>

Upvotes: 2

Related Questions