如何在jquery中添加匹配字符后的元素?

时间:2016-10-10 00:14:03

标签: javascript jquery

如果元素具有特定数量的字符,则尝试在文本中匹配第二个或更多点后放置元素。例如:

<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> 

...输出结果为:

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

4 个答案:

答案 0 :(得分:1)

你可以试试这个

&#13;
&#13;
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
}
&#13;
span{
  color: red;
}
&#13;
<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>
&#13;
&#13;
&#13;

  

注意:如果你只需要在chars之后替换下一个点就可以了   使用'.'代替/\./g

答案 1 :(得分:0)

这样:使用JQUERY Substring

    <p>
    this is test string with jquery . test 1  2 3 4 45 5 . test test test
    </p>
    <b></b>


    <script>
    var a = $('p').text();
    var _output = '';
    var _allow_index = 40;
    if (a.length > _allow_index)
    {
      var x = a.split('.');
      for(var i=0; i<x.length; i++)
        { if (_output.length < _allow_index) { _output+=x[i]+'.'; } }
    }
    else { _output = a; }
    $('b').html(_output + '<br>'+a.substr(_output.length,a.length));
    </script>

答案 2 :(得分:0)

这样做似乎不是一个很好的做法,例如长度可能因本地化语言而异。 此外,您假设您有纯文本,而不是HTML文本,并且两种情况下的长度都不同。您可能希望使用html()而不是text()。 然而,这是给定案例的一种方式:

synchronize()

答案 3 :(得分:0)

您只需要在CSS中添加此属性。

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

word-wrap: break-word;
 }
</style>