簡體   English   中英

用JavaScript字符串寫雙引號

[英]Writing double quotes in javascript string

我正在使用一種方法來迭代執行字符串中的替換。

function replaceAll(srcString, target, newContent){
  while (srcString.indexOf(target) != -1)
  srcString = srcString.replace(target,newContent);
  return srcString;
}

但這不適用於我想要的目標文本,主要是因為我無法考慮如何正確編寫該文本:從字面上看,我想刪除的是"\\n" ,(包括逗號和引號),那么什么才能作為第二個參數傳遞才能使其正常工作?

提前致謝。

如果將第一個參數replace為雙引號,則需要轉引號

'some text "\\n", more text'.replace("\\"\\n\\",", 'new content');

或者你可以做

'some text "\\n", more text'.replace('"\\n",', 'new content');

請注意,在第二個示例中,replace的第一個參數使用單引號表示字符串,因此您無需轉義雙引號。

最后,另一個選擇是在replace調用中使用正則表達式

'some text "\\n", more text "\\n",'.replace(/"\\n",/g, 'new content');

末尾的“ g”表示全部替換(全局)。

要刪除"\\n" ,只需使用String.replace

srcString.replace(/"\n"[,]/g, "")

您可以使用正則表達式/"\\n"[,]/g替換

不需要這種功能。 replace函數有一個額外的參數g ,它將替換所有出現的內容,而不是第一個出現的內容:

'sometext\nanothertext'.replace(/\n/g,'');

不管字符串中的引號是否被轉義:

 var str = 'This string has a "\n", quoted newline.';

要么

var str = "This string has a \"\n\", escaped quoted newline.";

解決方法是相同的(將“ !!!”更改為要替換為"\\n",用:

 str.replace(/"\n",/g,'!!!');

jsFiddle演示

暫無
暫無

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

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