簡體   English   中英

Javascript 替換所有出現的

[英]Javascript replace all occurrences

我需要用javascript中的字符轉換字符串的子字符串。

我使用以下代碼來做到這一點

av_text_to_display = av_text_to_display.replace("a*^!", "'");

但它只能替換第一次出現。 我對所有事件都使用了以下代碼

av_text_to_display = av_text_to_display.replace("a*^!", "'", "g");

但這不是標准方式。 這樣做的標准方法是什么?

您正在使用字符串而不是 RegExp 進行搜索,它可能應該是:

av_text_to_display.replace(/a*\^!/g, "'");

如果您嘗試替換該文字字符串,而不是匹配該字符串的正則表達式,請使用轉義正則表達式:

av_text_to_display = av_text_to_display.replace(/a\*\^!/g, "'");

 var av_text_to_display = "here: a*^!, there: a*^! and also here, twice: a*^!a*^!"; av_text_to_display = av_text_to_display.replace(/a\\*\\^!/g, "'"); console.log(av_text_to_display);

如果您不想使用正則表達式,您可以同時使用splitjoin函數來執行此操作:

your_string.split("a").join("'");

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM