JQuery intercepts the specified length string code, jquery string
For example, extract the string code.
<! Doctype html>
The code above provides the function of intercepting strings.
I. Implementation Principle
Get the length of the text in the div, and compare it with the length specified by the limit attribute. If the length exceeds the limit, the specified length is truncated and replaced.
Ii. Code comments
1. jQuery. fn. limit = function () {}, used to extend an instance function for jQuery. The jQuery object can call this function.
2. var self = $ ("div [limit]"), used to obtain a set of div objects with the limit attribute.
3. self. each (function () {} allows the obtained div object set to traverse and execute a specified function.
4. var objString = $ (this). text (), get the text content in the div element. Here this refers to when the each () function traverses the current div.
5. var objLength = $ (this). text (). length, get the length of the text content in the current div.
6. var num = $ (this). attr ("limit") to obtain the limit attribute value in the div. The specified character length is used here.
7. if (objLength> num) {}, the text content length in div is greater than the specified length, which executes the specified code.
8. $ (this). attr ("title", objString), set the title attribute value of the div to the content in the div.
9. objString = $ (this). text (objString. substring (0, num) + "..."), truncate the specified length string, and use the ellipsis instead of the excess.
How to Use jquery to intercept a string of a specified length in Chinese and English?
Jquery does not have this function, and js already has
Var str = "Hello world! "
Document. write (str. substr (3, 7 ))
Output:
Lo worl
Reference: w3school.com.cn/js/jsref_substr.asp
How to intercept a specific string in jQuery
Case Sensitive! IndexOf
<Script language = "javascript" type = "text/javascript">
Function ck (txt ){
If (txt. indexOf ('tickets ')>-1 ){
Return 'tickets ';
}
Return txt;
}
Var a = "aaaa ticket bcd ";
Var B = "abasddsfsf ";
Alert (ck ());
Alert (ck (B ));
</Script>