replace first and last occurrence of a character
I need a regex for so as to convert the string {somestr}
to :somestr
, but I need to replace only the first and the last occurrences of curly braces, since if there is any occurrence in the middle of a string - it should not be removed.
So far I have tried:
the incoming string var path = '/claims/{id}'
var pathWithoutBraces = path.replace("{", ":").replace("}", "")
The output is /claims/:id
which is what expected, but still it will replace all the further occurences in the whole string
您可以使用以下内容替换第一个和最后一个{
和}
var s='/claims/{abc{de}}f}';
document.write(s.replace(/{(.*)}/,':$1'));
这应该只取代第一个和最后一个大括号:
str.replace(/({)(.*)(})/, ':$2');
How about: /({)([}w]+)(})/
? See https://regex101.com/r/pW4fU7/2
This will demand and capture an opening and closing curly bracket, and also will capture word characters (and closing curly brackets) in between. Here's a snippet for your example:
var path = '/claims/{id}';
document.write(path.replace(/({)([}w]+)(})/,':$2'));
链接地址: http://www.djcxy.com/p/59514.html
上一篇: 我如何才能在powershell中的子字符串中替换特定字符
下一篇: 替换字符的首次和最后一次出现