2016-10-10 3 views
-2

특정 문자 수만큼 텍스트에 두 번째 이상의 점이 일치하면 요소를 배치하려고합니다. 예 :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. 
+0

이렇게하지 마십시오. CSS를 사용하여 컨테이너의 너비를 정의하십시오. – user2182349

+0

예, 알고 있습니다. 하지만이 jquery 사용해야합니다 ..
그냥 예입니다. divs 및 다른 요소 같은 다른 요소를 배치 할 것이다. –

답변

1

당신이

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>
을 시도 할 수 있습니다

참고 : 당신은 단지 인스턴스 길이, 매우 좋은 연습이 될 것 같지 않습니다를 수행 할 수 있습니다 사용 '.' 대신 /\./g

0

이 방법은 : JQuery와 하위 문자열로

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

의 문자 한 후 다음 하나 개의 점을 교체해야하는 경우 현지화 된 언어에 따라 다를 수 있습니다. 게다가, 당신은 HTML 텍스트가 아닌 평범한 텍스트를 가지고 있고 길이가 다른 경우를 가정하고 있습니다. text() 대신 html()을 사용할 수 있습니다. 그러나 여기에 주어진 경우에 대한 방법이 있습니다 :

var container = $('#mytext'); 
var length = 55; 
var insert = '<br/>'; 
var text = container.text().trim(); // text() or html() 
var dotPosAfterLength = text.indexOf(".", length); 
if (dotPosAfterLength != -1) { 
    container.html(
     text.substring(0, dotPosAfterLength+1) 
     +insert 
     +text.substring(dotPosAfterLength+1) 
    ); 
} 
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> 
관련 문제