更新时间:2023-11-07 21:49:40
使用match
:
a.match(/\$.*?\$/g);
这将返回一个包含所有值的数组.您也可以使用
This returns an array with all the values. You can also use
a.match(/\$.*?\$/g)||[];
确保始终有一个数组,因为如果没有匹配项,则会得到null
对象,该对象并不总是有用的.
to make sure that you’ve always got an array because if there’s no match you’ll get the null
object which is not always useful.
正则表达式在我的答案中也得到了类似的解释:匹配任何内容(.
),任意次数(*
),尽可能少的次数(?
).
The RegExp is also explained in an answer of mine to a similar question: match anything (.
), any number of times (*
), as few times as possible (?
).
然后,您可以使用join
将该数组连接为字符串:
Then you can use join
to join that Array into a String:
(a.match(/\$.*?\$/g)||[]).join(',');
代码:
var a='Dear $name$, This is my number $number$. This is my address $address$ Thank you!';
var b=(a.match(/\$.*?\$/g)||[]).join(',');
输出:
"$name$,$number$,$address$"
有效地,在这种情况下,正则表达式匹配每个$
,然后匹配直到下一个$
的所有字符,最后匹配末尾的美元符号.如果在末尾指定g
(全局)标志,则match
将给出结果列表.
Effectively, in this case the regular expression matches every $
followed by anything up to the next $
and finally that dollar sign at the end. And match
will give a list of results if you specify the g
(global) flag at the end.
由于这是一个字符串(以及上面的正则表达式)文字,因此不会干扰jQuery的$
符号.唯一重要的是用反斜杠(\$
)来转义该符号,因为它在RegExp中具有特殊含义.
As this is a string (and the above a regular expression) literal, there’s no interference with jQuery’s $
symbol. The only important thing is to escape that symbol with a backslash (\$
) because it has a special meaning in RegExp.