JS + body rules highlighted search keywords (2)

Source: Internet
Author: User
[Original] JavaScript highlighted search keywords (Simplified Version)

[16:25:00] By mwfls

11.

. Maks {Line-Height: 150%; padding: 10px ;}. maks P {margin-bottom: 10px; text-indent: 2em ;}. maks IMG {margin-bottom: 10px; margin-top: 10px ;}. maks. IMP {font-size: 14px; font-weight: bold ;}

If your article is too long, it's like the article I included [different performance of JS and CSS in IE and Firefox]. Basically, at a resolution of 1280*1024, you have to roll the scroll wheel three times to see the end, it is very inconvenient for users to find the content they want.

To improve user performance, the best way is to highlight the content that the user wants to search in the article.

Next, let's take a step-by-step look at how to implement this function (the idea of how to implement it is still relatively simple, but it has been a whole day since JavaScript was actually used, there are textbooks and articles on the Internet for implementing such functions, but I think there is still room for improvement, so the idea is similar, but the implementation method is changed .)

Step 1: extract keywords searched by users

When a user searches for keywords through a search engine, the searched keywords are transmitted through URL encoding and finally displayed in the address bar, such as search: Flash as3 progress bar Mak-S

Google: http://www.google.cn/search? Hl = ZH-CN & newwindow = 1 & client = aff-OS-Maxthon & HS = ugn & Q = flash + as3 + % E8 % BF % 9B % E5 % Ba % A6 % E6 % 9d % A1 + Mak-S & meta = & AQ = F & OQ =

Yahoo Display Results: http://one.cn.yahoo.com/s? P = flash + as3 + % E8 % BF % 9B % E5 % Ba % a6 % E6 % 9d % A1 + Mak-S & V = web & pid = HP

Baidu Display Results: http://www.baidu.com/s? WD = flash + as3 + % BD % F8 % B6 % C8 % CC % F5 + Mak-S

Note that the red part of the code is the URL-encoded keyword. Each keyword is connected with "+". English numbers and some characters remain unchanged, and Chinese characters are changed to "% xx. The red part is what you will use later.

Then, the user enters your website and blog through the search page, and the browser will record the user entering your website from that page. You can use the JavaScript document. the referrer function calls this page address (this value is blank if the user directly enters your website ).

After obtaining the address, we will extract the user's search keywords from the address. In this step, we will use indexof to determine the number of keywords on the Internet. Although this can be achieved, it will be complicated in my opinion. So I changed it from here and used regular expressions to judge and extract keywords. The Code is as follows:

View plain print?
  1. VaR rehost =/[/W] +: // [/W/.] + ///;
  2. VaR arrdata = (rehost. Test (URL ))? (URL. Match (rehost) [0]. indexof ("yahoo")> 0 )? (URL. Match (/[&/?] P = [/W + %] +/) [0]. split (/=/) [1]. match (/[^/+] +/G) :( (URL. match (rehost) [0]. indexof ("google")> 0 )? (URL. match (/& Q = [/W + %] +/) [0]. split (/=/) [1]. match (/[^/+] +/G) :( null)

VaR rehost =/[/W] +: // [/W/.] + ///; <br/> var <br/> arrdata = (rehost. test (URL ))? (URL. Match (rehost) [0]. indexof ("yahoo")> 0 )? (URL. Match (/[&/?] P = [/W + %] +/) [0]. split (/=/) [1]. match (/[^/+] +/G) :( (URL. match (rehost) [0]. indexof ("google")> 0 )? (URL. match (/& Q = [/W + %] +/) [0]. split (/=/) [1]. match (/[^/+] +/G) :( null) <br/>

The URL is the result of document. referrer, and arrdata is the array of the filtered keywords (which has not been deserialized) through regular addition ). The "Regular Expression" is too powerful. If you have time, you need to study it again. This is the regular expression that I wrote for the first time. If there is something wrong with it, please leave a message.

After obtaining the keyword through the above expression, the next step is to recode the keyword. You can use the decodeuricomponent function in JavaScript to restore it to the keyword we previously searched: Flash as3 progress bar Mak-s. (If you do not understand URL encoding, refer to this article: [javascript URL encoding function])

Code:

View plain print?
  1. VaR arrkey = new array ();
  2. For (VAR I = 0; I <arrdata. length; I ++ ){
  3. Arrkey [I] = decodeuricomponent (arrdata [I]);
  4. }

VaR arrkey = new array (); <br/> for (VAR I = 0; I <arrdata. length; I ++) {<br/> arrkey [I] = decodeuricomponent (arrdata [I]); <br/>}< br/>

In this way, the original search keyword is in the arrkey. At this point, the work of extracting keywords is OK!

Step 2: highlight keywords in your content

This step is implemented on the Internet by traversing the children in the body to find the highlighted content. However, I think this is not scientific. First, the keywords that users need to search for are generally in the content of the article or in the document list, such as those headers, it is already very "highlighted" and does not need to be highlighted again. In this way, we can narrow down the scope to be searched-the content and list of articles.

How can we locate the highlighted content in the body and list? It is determined by ID and getelementbyid. For example, if the ID of the DIV in the list is set to "MList", the document in Javascript will be used. getelementbyid ("MList "). innerhtml can easily obtain the content in the list.

However, innerhtml is used to obtain the source code of the webpage, including the HTML tag, which should be highlighted by the webpage content. So here I use a regular expression to determine whether the webpage belongs to the HTML Tag, then, replace + regular expression is used to replace the highlighted keyword, which is convenient and convenient.

Function Code with highlighted keywords:

View plain print?
  1. // OBJ: the ID of the search range.
  2. // Keyword: keyword array, that is, the preceding arrdata
  3. // Kstyle: highlighted style, that is, style characters in the style, as you like
  4. Function highlighttext (OBJ, keyword, kstyle)
  5. {
  6. If (kstyle)
  7. {
  8. For (VAR I = 0; I <keyword. length; I ++ ){
  9. VaR Reg = new Regexp (keyword [I] + "(? = [^ <>] * <) "," Ig "); // dynamically generates a regular expression based on the keyword
  10. VaR DATA = Document. getelementbyid (OBJ). innerhtml; // obtain the source code by replacing the range.
  11. Document. getelementbyid (OBJ ). innerhtml = data. replace (Reg, '<span style = "' + kstyle + '">' + keyword [I] + '</span>'); // replace according to the Regular Expression
  12. }
  13. }
  14. }

// OBJ: <br/> search range id <br/> // Keyword: keyword array, that is, the preceding arrdata <br/> // kstyle: highlighted style, that is, style characters in the style, as you like <br/> function highlighttext (OBJ, keyword, kstyle) <br/>{< br/> If (kstyle) <br/> {<br/> for (VAR I = 0; I <keyword. length; I ++) {<br/> var Reg = new <br/> Regexp (keyword [I] + "(? = [^ <>] * <) "," Ig "); // dynamically generates a regular expression based on the keyword <br/> var DATA = document. getelementbyid (OBJ ). innerhtml; // obtain the source code by replacing the range <br/> document. getelementbyid (OBJ ). innerhtml = data. replace (Reg, '<span <br/> style = "' + kstyle + '">' + keyword [I] + '</span> '); // Replace with the regular expression <br/>}< br/>

Step 3: Use the program and precautions

Through the above two steps, you should understand the process of this program. Add these programs to the window. in the onload event (remember window. onload is not body. onload, because the IF and FF onload events are a little different, so the two are compatible, meaning that the program is executed after the webpage is loaded ).

Complete program code

View plain print?
  1. // URL: the URL returned by document. referrer;
  2. // KUNM: Number of keywords to be highlighted
  3. // Extract the keyword function checkurl
  4. Function checkurl (URL, knum ){
  5. VaR rehost =/[/W] +: // [/W/.] + ///;
  6. VaR arrdata = (rehost. Test (URL ))? (URL. Match (rehost) [0]. indexof ("yahoo")> 0 )? (URL. Match (/[&/?] P = [/W + %] +/) [0]. split (/=/) [1]. match (/[^/+] +/G) :( (URL. match (rehost) [0]. indexof ("google")> 0 )? (URL. match (/& Q = [/W + %] +/) [0]. split (/=/) [1]. match (/[^/+] +/G) :( null)
  7. Knum = (arrdata )? (Knum )? (Knum <arrdata. Length )? (Knum) :( arrdata. Length) :( 3) :( null );
  8. If (! Knum) return;
  9. VaR arrkey = new array ();
  10. For (VAR I = 0; I <knum; I ++ ){
  11. Arrkey [I] = decodeuricomponent (arrdata [I]);
  12. }
  13. Return arrkey;
  14. }
  15. // Highlighttext
  16. Function highlighttext (OBJ, keyword, kstyle)
  17. {
  18. If (kstyle)
  19. {
  20. For (VAR I = 0; I <keyword. length; I ++ ){
  21. VaR Reg = new Regexp (keyword [I] + "(? = [^ <>] * <) "," Ig ");
  22. VaR DATA = Document. getelementbyid (OBJ). innerhtml;
  23. Document. getelementbyid (OBJ ). innerhtml = data. replace (Reg, '<span style = "' + kstyle + '">' + keyword [I] + '</span> ');
  24. }
  25. }
  26. }
  27. // Call the main function highlightmain
  28. Function highlightmain (){
  29. If (! Document. referrer) return;
  30. Highlighttext ('here your search range is 1', checkurl (document. referrer, 5), "background-color: # 0066cc; color: # fff ");
  31. Highlighttext ('here your search range is 2', checkurl (document. referrer, 5), "Your highlighted style ");
  32. }
  33. Window. onload = function () {highlightmain ()}; // Add the main function to the window. onload event.

// URL: document. referrer <br/> returned webpage address; <br/> // KUNM: number of keywords to be highlighted <br/> // extract the keyword function checkurl <br/> function checkurl (URL, knum) {<br/> var rehost =/[/W] +: // [/W/.] + ///; <br/> var <br/> arrdata = (rehost. test (URL ))? (URL. Match (rehost) [0]. indexof ("yahoo")> 0 )? (URL. Match (/[&/?] P = [/W + %] +/) [0]. split (/=/) [1]. match (/[^/+] +/G) :( (URL. match (rehost) [0]. indexof ("google")> 0 )? (URL. match (/& Q = [/W + %] +/) [0]. split (/=/) [1]. match (/[^/+] +/G) :( null) </P> <p> knum = (arrdata )? (Knum )? (Knum <arrdata. Length )? (Knum) :( arrdata. Length) :( 3) :( null); <br/> If (! Knum) return; <br/> var arrkey = new array (); <br/> for (VAR I = 0; I <knum; I ++) {<br/> arrkey [I] = decodeuricomponent (arrdata [I]); <br/>}< br/> return arrkey; <br/>}< br/> // The highlighted keyword function highlighttext <br/> function highlighttext (OBJ, keyword, kstyle) <br/>{< br/> If (kstyle) <br/>{< br/> for (VAR I = 0; I <keyword. length; I ++) {<br/> var Reg = new Regexp (keyword [I] + "(? = [^ <>] * <) "," Ig "); <br/> var DATA = document. getelementbyid (OBJ ). innerhtml; <br/> document. getelementbyid (OBJ ). innerhtml = data. replace (Reg, '<span <br/> style = "' + kstyle + '">' + keyword [I] + '</span> '); <br/>}< br/> // The main function highlightmain called <br/> function highlightmain () {<br/> If (! Document. referrer) return; </P> <p> highlighttext ('here your search range is 1', checkurl (document. referrer, 5), "background-<br/> color: # 0066cc; color: # fff"); <br/> highlighttext ('here your search range is 2 ', checkurl (document. referrer, 5), "Your highlighted style"); <br/>}< br/> window. onload = function () {highlightmain ()}; // Add the main function to the window. onload event

In the complete code, I add one more function, that is, the number of keywords you need to highlight. If you do not enter the knum variable, three keywords are set by default, in my statistics, the keyword entered by users is usually about two to four. In addition, I do not recommend that you put this code on the homepage [makstudio] or some pages that are not too rich in content [intelligent commerce games [Sudoku]. this is because the highlighted keywords affect the design style of the webpage. In use, you only need to put this code slightly modified at the bottom of your webpage or article source code.

Last display:

Note:

1. The program in the IE7-5.5, FF test passed, not in other browsers for testing, conditional friends can help to test, if there is a problem, please leave a message for me.

2. do not place <style type = text/CSS> XXXX </style> or other CSS or script code within the search range. Otherwise, the XXXX code may be replaced with the content, the result will make your page unrecognizable.

3. This program only determines the search keywords of Google and Yahoo! Because Baidu's URL encoding is different from the previous two, so no decoding method matching the encoding is made for the moment. If you have a better way, you can leave a message for me.

4. The above are the problems found by the author for the time being. If you encounter more problems during use, leave a message and I will try my best to help solve them.

5. This program is purely personal interest. If you need it, you can modify it or leave a message.

This program extends the Function Idea (if you are interested, try to make it)

1. generate dynamic keyword Navigation Based on search keywords.

2. Use different highlighted styles based on different keywords to simulate web snapshots of search engines.

3. The function of extracting keywords is enhanced for Chinese and English word segmentation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.