[英]regex replace characters with html tag in string
我遇到了需要用輸入標簽替換的正則表達式單詞。 但是,當我添加html時,它讀取為純字符串。
這是我的字符串:“您好,我的名字是/#Ann#/。我正在為/#IStaff#/工作,請您給我回電話”。 我在哪里做錯了?
editModalText() {
const { modalMessage } = this.state
let regex = /\/#(.*?)#\//g
let replaced = modalMessage.replace(regex, '<input type="text">')
return replaced
}
<div>{this.editModalText()}</div>
這是因為它是純字符串。
如果要將JSX語法混合到模板中,則必須完全更改方法。
例如,構建一個令牌生成器 ,它將您的字符串轉換為類似以下的數組:
[
"Hello, my name is ",
"/# Ann #/",
". I'm working for ",
"/# IStaff #/",
", could you please call me back"
]
然后循環遍歷並將原始字符串或適當的JSX元素推入新數組,最后返回該數組。
您可以使用.*?
來匹配中間部分.*?
。
let modalMessage = "Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back"; let regex = /\\/#(.*?)#\\//g; let replaced = modalMessage.replace(regex, "<input />"); console.log(replaced);
另外,您還需要在正則表達式中使用反斜杠(\\)來轉義/
。
有效表達式以/
開頭和結尾:
/<regex>/<flags>
因此,在您的示例中:
/ // <- Start of Regular expression
\/ // <- Match /
# // <- Match #
(.*?) // <- Match the middle part (non-greedy)
# // <- Match #
\/ // <- Match /
/g // <- End regex and set "global" flag
HTML示例:
let modalMessage = "Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back"; let regex = /\\/#(.*?)#\\//g; let replaced = modalMessage.replace(regex, '<input type="text">'); document.write(replaced);
您不會在占位符周圍引起誤解(/是需要轉義的正則表達式特殊字符)
使用(.+)
或(.*)
將提供貪婪的匹配。 這意味着,它將盡可能匹配,這就是為什么匹配太多的原因。 您要使用惰性匹配(貪婪的反面,它會盡快停止), (.+?)
或(.*?)
您可以使用以下一個:
let modalMessage = "Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back" let regex = /\\/#(.*?)#\\//g let replaced = modalMessage.replace(regex, '<Input />') console.log(replaced)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.