I have trouble with changing round bracket tag in Javascript. I try to do this:
开发者_JAVA百科var K = 1;
var Text = "This a value for letter K: {ValueOfLetterK}";
Text = Text.replace("{ValueOfLetterK}", K);
and after that I get:
Text = "This a value for letter K: {ValueOfLetterK}"
What can be done to make this work? When I remove round brackets it works fine.
To replace more than one occurrence, you need a regular expression with 'g' (=global) switch
Text = Text.replace(/{ValueOfLetterK}/g, K);
If you're looking for a more generic way to replace placeholders in the string, this is how it could be done:
var myVars = { A: 1, B: 2 };
var Text = "This a value for a {valueOfA} and b {valueOfB} and a again {valueOfA}";
Text = Text.replace(/{valueOf(\w+)}/g, function() {
var varName = arguments[1];
return myVars[varName];
});
alert(Text)
It works for me in Chrome and Firefox... Try to escape curly braces and see what happens:
Text = Text.replace("\{ValueOfLetterK\}", K);
I don't see any problem with your code. I tried it in Firefox and IE, and it worked for me. Let me know witch browser yor are using.
<html>
<head>
<script>
var K = 1;
var Text = "This a value for letter K: {ValueOfLetterK}";
Text = Text.replace("{ValueOfLetterK}", K);
alert(Text)
</script>
</head><body>
</body>
</html>
精彩评论