2016-10-10 5 views
-2

特定の文字数のテキストが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を使う必要があります。
は単なる例です。私はdivや他の要素のような別の要素を配置します。 –

答えて

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

の文字の後に次の1個のドットを交換する必要がある場合ローカライズされた言語によって異なる場合があります。 さらに、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> 
関連する問題