首先,对不起,如果我的问题有点令人困惑,英语不是我的母语,所以我需要用该列表的第一个URL替换一堆URL,这些URL一直在变化,这是我想要的文本代替:
[rotate=url1.usa.gov;url2.facebook.com/;http://9gag.com]
唯一不变的是[rotate=....]
,URL被一个;
I分割,我希望结果是:
url1.usa.gov
这是我尝试过的:
var str = str.replace(/\[rotate=.*;.*\]/g, '$0');
但是,当我这样做时,结果是:$0
我该怎么做?
.replace
从$
替换字符串开始解释许多特殊序列,但$0
不是其中之一。
如果要从匹配中提取子字符串,则需要捕获组((
... )
)。凡是由他们匹配的是作为以及匹配对象的属性$1
,$2
......在一个替换字符串。
在你的情况下,我会去
str.replace(/\[rotate=([^;\]]*)(?:;[^\]]*)?\]/g, '$1')
那是:
\[rotate= // find '[rotate=', followed by
( [^;\]] * ) // 0 or more characters that are not ';' or ']'
// (and remember this part as $1),
(?: // group, but don't capture
; // a literal ';'
[^\]] * // 0 or more characters that are not ']'
)? // this group is optional
\] // a literal ']'
即使列表中只有一个URL,它也很可靠:[rotate=example.com]
将变为example.com
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句