Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - regular expression replace multiple matching pattern with link

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

  1. put the search result in an array,
  2. if the array is not empty, construct the text string of the link for each element in the array,
  3. do a loop to find each occurrence again and replace it with the link

But is there any way to do this regular expression just in one line with JavaScript and/or JQuery?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the following here.

var result = str.replace(/(XXd+)/gi, "<A HREF='http://server.com/$1'>$1</A>");

Working Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...