admin管理员组

文章数量:1429953

What will be the regular expression to match {0} in a piece of text? so that if I have

 var temp = 'this is my {0} attempt';

I could use that regular expression in javascript to get the {0} out of 'temp', and replace with whatever text I want.

Thanks

What will be the regular expression to match {0} in a piece of text? so that if I have

 var temp = 'this is my {0} attempt';

I could use that regular expression in javascript to get the {0} out of 'temp', and replace with whatever text I want.

Thanks

Share Improve this question asked Apr 25, 2011 at 15:02 zoom_pat277zoom_pat277 1,2245 gold badges15 silver badges31 bronze badges 3
  • I've answered to your question, but take this hint: if you google "javascript string replace" you get plenty of examples and alternatives. Google is your friend. Really. – gd1 Commented Apr 25, 2011 at 15:06
  • @Giao the point of Stackoverflow is to be a site that contains information for Google searches to find! – Pointy Commented Apr 25, 2011 at 15:10
  • 1 Not when this information is already everywhere. Polluting S.O. with "how can I print an integer in C?" and "is there any way I can open a window in javascript" is not producing good, useful, reusable information. But here we are. – gd1 Commented Apr 25, 2011 at 15:12
Add a ment  | 

3 Answers 3

Reset to default 5
temp = temp.replace("{0}", "your text")

Regex is definitely not needed for this!

Ofcourse, you can do the following as well:

temp = temp.replace(/{\d+}/, "your text")

Response to @Giao:

temp = temp.replace("{\d+}", "your text")

will not replace anything. {\d+} is treated as a string and not regex

If you want to replace with something based on what the number is inside the curly braces, you could do this:

var replaced = original.replace(/\{(\d+)\}/g, function(_, digits) {
  return getReplacement(Number(digits));
});

You'd then write the function "getReplacement()" to return something based on the index from the original string.

/\{\d\}/

                                

本文标签: regexjavascript regular expression to match 0Stack Overflow