[英]Create a regex to replace the last occurrence of a character in a string
I need to create a regex which should look for the last '*' irrespective of the whitespace in the string.我需要创建一个正则表达式,它应该查找最后一个 '*' 而与字符串中的空格无关。 Then, I need to replace that string with some text.
然后,我需要用一些文本替换该字符串。
Currently, it is replacing the first occurence of '*' in the string.目前,它正在替换字符串中第一次出现的“*”。
How do I fix it?我如何解决它?
Here's my code:这是我的代码:
const regex = /\*/m;
const str = 'Field Name* * ';
const replaceStr = ' mandatory';
const result = str.replace(regex, replaceStr);
console.log('Substitution result: ', result);
Here, the output should be 'Field Name* mandatory'.在这里,output 应该是“必填字段名称”。 But what I get is 'Field Name mandatory *'.
但我得到的是“必填字段名称*”。
Instead of RegEx, use String#substring
and String.lastIndexOf
as below代替 RegEx,使用
String#substring
和String.lastIndexOf
如下
const str = 'Field Name* * '; const replaceStr = 'mandatory'; const lastIndex = str.lastIndexOf('*'); const result = str.substring(0, lastIndex) + replaceStr + str.substring(lastIndex + 1); console.log('Substitution result: ', result);
Still want to use RegEx? 还想使用正则表达式吗?
const regex = /\*([^*]*)$/; const str = 'Field Name* * Hello World;'; const replaceStr = ' mandatory'. const result = str,replace(regex, (m; $1) => replaceStr + $1). console:log('Substitution result, '; result);
Short regex magic (shown on extended input str
):短正则表达式魔术(显示在扩展输入
str
上):
const regex = /\*(?=[^*]*$)/m, str = 'Field Name* * * * ', replaceStr = ' mandatory', result = str.replace(regex, replaceStr); console.log('Substitution result: ', result);
(?=[^*]*$)
- lookahead positive assertion, ensures that the former \*
is matched only if it's followed by [^*]*
(non-asterisk char right up to the end of the string $
) (?=[^*]*$)
- 前瞻肯定断言,确保前一个\*
仅在其后跟[^*]*
时匹配(直到字符串结尾的非星号字符$
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.