I have text fields that contains one or multiple occurrence of some code like "XX00123" or "XX00456", for example,
The XX00123 is a sibling of XX00456 and parent of XX00789
I would like to use regex to replace each occurrence of the code thing with a link to it. The result of above example would be then,
The <A HREF='http://server.com/XX00123'>XX00123</A> is a sibling of <A HREF='http://server.com/XX00456'>XX00456</A> and parent of <A HREF='http://server.com/XX00789'>XX00789</A>
I think I could do it with
But is there any way to do this regular expression just in one line with JavaScript and/or JQuery?
You can use the following here.
var result = str.replace(/\b(XX\d+)\b/gi, "<A HREF='http://server.com/$1'>$1</A>");
You could use something like this:
var re = /([X0-9]+)/gi;
var result = str.replace(re, "<A HREF='http://server.com/$1'>$1</A>");
The regex
will match one or more x
followed by numbers until a space or a non-numeric value.
With the following code,
var result = str.replace(/(XX(\d{5}))/ig, "<A HREF='server.com/$2'>$1</A>");
The result would be,
The <A HREF='http://server.com/00123'>XX00123</A> is a sibling of <A HREF='http://server.com/00456'>XX00456</A> and parent of <A HREF='http://server.com/00789'>XX00789</A>
The $1 represents "(XX(\\d{5}))" - the out side pair of parentheses, and the $2 represents "(\\d{5})" - the inside pair of parentheses.
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.