简体   繁体   English

正则表达式用链接替换多个匹配模式

[英]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, 我的文本字段包含一个或多个“ XX00123”或“ XX00456”之类的代码,例如,

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? 但是,有什么方法可以仅使用JavaScript和/或JQuery来完成此正则表达式吗?

You can use the following here. 您可以在此处使用以下内容。

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

Working Demo 工作演示

You could use something like this: 您可以使用如下形式:

var re = /([X0-9]+)/gi; 
var result = str.replace(re, "<A HREF='http://server.com/$1'>$1</A>");

REGEX101 REGEX101

The regex will match one or more x followed by numbers until a space or a non-numeric value. regex将匹配一个或多个x后跟数字,直到空格或非数字值为止。

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. $ 1表示“((XX(\\ d {5}))””-括号的外侧,而$ 2表示“(\\ d {5})”-括号的内侧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM