2017-05-26 68 views
0

我正在使用sanitize-html來清除draftJS編輯器的粘貼文本。如何用javascript替換HTML字符串中的字符

比方說,結果可能是文本字符串,這樣

<h1 class="title"> President said "<b>Give this man a money</b>" and i agree </h1

現在我需要«»取決於條件,以取代"。 我應該怎麼做。我試圖弄清楚我是否可以用draftJSContentBlock方法做到這一點,但它看起來太複雜了。所以我認爲修改html字符串更容易。

回答

2

你可以用兩個正則表達式做到這一點我想:

var inputString = `<h1 class="title"> 
 
     President said "<b>Give this man a money</b>" and i agree 
 
    </h1>` 
 
     , startingQuoteRE =/"/g 
 
     , endingQuoteRE = /" /g 
 
     , outputString = '' 
 
     ; 
 
    outputString = inputString.replace(startingQuoteRE, " «"); 
 
    outputString = outputString.replace(endingQuoteRE, "» "); 
 
    // Or by chaining .replace 
 
    // outputString = inputString.replace(startingQuoteRE, " «").replace(endingQuoteRE, "» "); 
 
    console.log(outputString);

+0

是不是有什麼關於不與正則表達式解析HTML? – 2017-05-26 09:54:58

+0

@Eldy是的,建議不要使用RegEx解析HTML。但在這裏我們不解析任何HTML,只是做一些字符串替換。 – Booster2ooo

0
  1. 創建replaceAll功能。因爲replace函數將取代唯一的第一次出現。

    String.prototype.replaceAll = function(string, replace) { 
    return this.split(string).join(replace); 
    }; 
    
  2. 調用這樣的函數。

    var str = '<h1 class="title">\ 
    President said "<b>Give this man a money</b>" and i agree\ 
    </h1>'; 
    var result = str.replaceAll('"','\''); 
    console.log(result);