[英]Regex: match last and second-last character
I need to wrap the two last characters in a string in a separate <span>
: 我需要将最后两个字符包装在单独的
<span>
中的字符串中:
-1:23 // This is what I have
-1:<span>2</span><span>3</span> // This is what I want
The following matches the last character – but how can I make it match the second last as well? 以下内容与最后一个字符匹配-但是如何使它也与倒数第二个匹配?
str.replace(/(.$)/, "<span>$1</span>");
Thanks :) 谢谢 :)
You may use 您可以使用
.replace(/.(?=.?$)/g, "<span>$&</span>")
See the regex demo 见正则表达式演示
If these must be digits, replace .
如果这些必须是数字,请替换
.
with \\d
: 与
\\d
:
.replace(/\d(?=\d?$)/g, "<span>$&</span>")
The pattern matches 模式匹配
\\d
- a digit \\d
一个数字 (?=\\d?$)
- that is followed with an end of string or a digit and end of string. (?=\\d?$)
-后面是字符串的末尾或数字和字符串的末尾。 The $&
is a replacement backreference that references the whole match value from the string replacement pattern. $&
是一个替换反向引用,它引用字符串替换模式中的整个匹配值。
JS demo: JS演示:
console.log("-1:23".replace(/.(?=.?$)/g, "<span>$&</span>")); console.log("-1:23".replace(/\\d(?=\\d?$)/g, "<span>$&</span>"));
Now, to make it more dynamic, you may use a limiting (range/interval) quantifier : 现在,为了使其更具动态性,您可以使用限制(范围/间隔)量词 :
function wrap_chars(text, num_chars) { var reg = new RegExp(".(?=.{0," + (num_chars-1) + "}$)", "g"); return text.replace(reg, "<span>$&</span>"); } console.log(wrap_chars("-1:23", 1)); // wrap one char at the end with span console.log(wrap_chars("-1:23", 2)); // wrap two chars at the end with span
You can add another group before the last one, which also matches a single character ( (.)
), then wrap each of them using references ( $1
and $2
): 您可以在最后一个组之前添加另一个组,该组也匹配一个字符(
(.)
),然后使用引用( $1
和$2
)包装每个组:
var str = '-1:23'.replace(/(.)(.)$/, '<span>$1</span><span>$2</span>') console.log(str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.