Patrick Teixeira Patrick Teixeira - 1 month ago 7
jQuery Question

How can I add element after match character in jquery?

Trying to place an element after match second or more dots in a text if it has a specific number of characters. Example:

<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you.
</div>

<script>
var chars = 55;

if ($('#mytext').text().length > chars){
//add <br> after first dot found after number of chars specified.
}
</script>


... The output would be:

This is just a example. I need to find a solution. I will appreciate any help.<br>
Thank you.

Answer

You can try this

var chars = 55;
if ($('#mytext').text().length > chars){
  var text = $('#mytext').text();        // div text
  var chars_text = text.substring(0, chars);   // chars text
  var rest = text.replace(chars_text, '').replace(/\./g,'. <span>After Dot</span>');  // rest of text and replace dot of rest text with span
  $('#mytext').html(chars_text+rest); // apply chars and rest after replace to the div again
}
span{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you. 
</div>

Note: if you just need to replace the next one dot after chars you can use '.' instead of /\./g

Comments