i have some strings like "de456" "us7515", it's de/us and 3 to 10 digits.
I wish to capture all of them and replace them with an hyperlink, unless they are already inside of a html tag.
example:
should change:
<div> de485 </div> => <div> <a href = "xxx.com/de485">de485</a></div> <span> i need us1234 </span> => <span> i need <a href = "xxx.com/us1234"> us1234 </a></span>
should not change:
<a href ="github.com/xxxxx/us1234> link </a> => <a href ="github.com/xxxxx/us1234> link </a>
should partially change
<a href ="github.com/xxxxx/us1234> us1234 </a> => <a href ="github.com/xxxxx/us1234> <a href = "xxx.com/us1234"> us1234 </a> </a>
I already wrote two regex:
to match text pattern:
de456
us1234
/\b(us\d{3,10}|de\d{3,10})\b/ig
to match text pattern inside of open html tag
<a href = "github.com/de456">
/<\s*\w.*\b(us\d{3,10}|de\d{3,10})\b.?>/ig
so I can do 1 and 2 by using jquery regex exec and string.replace, but i don't know how to do 3. Please advise. Thank you very much in advance.
I try this. Please take if necessary.
(?<![\/])((?:de|us)[0-9]{3,10})
SEE DEMO: http://regex101.com/r/oS0tS3/2
The following example is close enough, however, I don't recommend doing this in a real application.
// matches all 3 cases
var pattern = /([^/])((us|de)\d+)/ig;
/* 1 */
'<span> i need us1234 </span>'.replace(pattern, '$1<a href="xxx.com/$2">$2</a>');
//=> "<span> i need <a href="xxx.com/us1234">us1234</a> </span>"
/* 2 */
'<a href ="github.com/xxxxx/us1234> link </a>'.replace(pattern, '$1<a href="xxx.com/$2">$2</a>');
//=> "<a href ="github.com/xxxxx/us1234> link </a>"
/* 3 */
'<a href ="github.com/xxxxx/us1234> us1234 </a>'.replace(pattern, '$1<a href="xxx.com/$2">$2</a>');
//=> "<a href ="github.com/xxxxx/us1234> <a href="xxx.com/us1234">us1234</a> </a>"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.