We need to use regular expressions to obtain addresses like img or href. Next I will introduce you to the process of getting URLs in img using js. I hope this will be helpful to you.
The solution is as follows:
The Code is as follows: |
Copy code |
Content. replace (/] * src = ['"] ([^'"] +) [^>] *>/gi, function (match ){ Console. log (match ); }); The output result is:
|
The entire img tag is obtained, but what I expect is the URL in src, so you only need to return the new address in function (match.
So, it's stuck here...
Later, Google searched for the keyword "javascript replace callback" and found "replace callback function with matches" in stackoverflow to know that function (match) has other parameters.
Then, change the code below to solve the problem.
The Code is as follows: |
Copy code |
Content. replace (/] * src = ['"] ([^'"] +) [^>] *>/gi, function (match, capture ){ Console. log (capture ); });
Output result:
/Images/logo.gif
|
Then Baidu finds another good instance.
The Code is as follows: |
Copy code |
<Script type = "text/javascript"> // The idea is divided into two steps: Author (yanue ). // 1. Match the image img Tag (that is, match all images) and filter other unwanted characters. // 2. cyclically match the image address (src attribute) from the matched results (in the img tag) Var str = "this is test string 123 and the end 33! // Match the image (g indicates matching all results. I indicates case-sensitive) Var imgReg =/|/>)/Gi; // Match the src attribute Var srcReg =/src = ['"]? ([^ '"] *) ['"]? /I; Var arr = str. match (imgReg ); Alert ('all arrays that have successfully matched images: '+ arr ); For (var I = 0; I <arr. length; I ++ ){ Var src = arr [I]. match (srcReg ); // Obtain the image address If (src [1]) { Alert ('matched image address' + (I + 1) + ':' + src [1]); } // Of course, you can also replace the src attribute If (src [0]) { Var t = src [0]. replace (/src/I, "href "); // Alert (t ); } } </Script> |