Home  >  Article  >  Web Front-end  >  Use js regular expressions to add links to keywords_javascript skills

Use js regular expressions to add links to keywords_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:31:381797browse

It is required to add the disease name in an HTML script to the link of the disease database, only add it once, and avoid hyperlinks or image links.

Initially used str.replace('diabetes', 'diabetes');

After searching for a long time, I couldn’t find the replacement effect. It turned out that there was a picture whose title contained diabetes, and it was posted first.

Therefore, the link and tags should be avoided, but tags such as

should not be avoided

Above picture:

Copy code The code is as follows:

s = "Look at a diabetes medical record first
"
"Dr. Wang of Diabetes
"
"Introduction to diabetes
Incidence of diabetes
Symptoms of diabetes
"
"
";
document.write(s);

a_reg = //i; //Regular for a link
img_reg = //i; //Regulations for image links to prevent the image’s title, alt and other attributes from including disease names from being mistakenly replaced
var ix = 0;

var arr_ele = [];
//First replace all the 2 type tags with {{index}}, then process the remaining text, and then replace the content of the tag back
while(true){
If(-1 == s.toLowerCase().indexOf('
break;
}  
a_match = s.match(a_reg);
If(a_match){
//console.log(a_match);
arr_ele.push(a_match[0]);
s = s.replace(a_reg, '{{' ix '}}');
                                    }  
img_match = s.match(img_reg);
If(img_match){
//console.log(img_match);
arr_ele.push(img_match[0]);
s = s.replace(img_reg, '{{' ix '}}');
                                    }  
console.log(s);
}

document.write('
-------------------------
Step 1: Replace the link with {{index} After }:
' s '
');

s = s.replace(/diabetes/i, "
diabetes");

document.write('
-------------------------
Step 2: After adding the disease database link:< br>' s '
');

if(arr_ele){
for(var i=0; i         s = s.replace('{{' i '}}', arr_ele[i]);
}  
}

document.write('
-------------------------
Step 3: After replacing the link back:< br>' s '
');


The above is all the code for adding links to keywords using js regular expressions. It’s simple. Friends in need can refer to it
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn