![](/img/trans.png)
[英]How can I match everything not in a character set with regex and jQuery?
[英]How can I add element after match character in 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.
你可以試試這個
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
這樣:使用 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>
這樣做似乎不是一個很好的做法,例如長度可能因本地化語言而異。 此外,您假設您有一個純文本,而不是 HTML 文本,並且兩種情況下的長度都不同。 您可能希望使用 html() 而不是 text()。 但是,對於給定的情況,這是一種方法:
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)
);
}
你只需要在 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.