>探討在 .cshtml 裡面定義了一些文字樣板要跟 js 共用 如下: ```csharp= @{ string template = "{0} 市場, {1} 產品"; } <script> const marketTemplate = '@Html.Raw(template)'; </script> ``` 但因為 js 沒有像 c# 一樣的 string.Format 方法,所以需要自訂方法使用 ```javascript= // 參考自 GPT function formatString(template, ...values) { return template.replace(/{(\d+)}/g, (match, index) => values[index]); } ``` 接著在使用上就可以如下: ```javascript= @{ string template = "{0} 市場, {1} 產品"; } <script> const marketTemplate = '@Html.Raw(template)'; const result = formatString(marketTemplate, "一級", "消費電子"); console.log(result); // "一級 市場, 消費電子 產品 " </script> ``` 為何要使用 @Html.Raw,是由於 razor 編碼的關係,在中文的情況下就會輸出不正確。 遇到弱掃資安問題的話,就需要採用別的方式進一步處理。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up