最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to replace character in HTML string with javascript - Stack Overflow

programmeradmin1浏览0评论

I'm using sanitize-html to clean pasted text for draftJS editor.

Lets say result might be text string like this

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

Now i need to replace " with « or » depends on conditions. How should i do that. I tried to figure out if i can do it with draftJS ContentBlock methods, but it seems way too plicated. So i think it is easier to modify html string.

I'm using sanitize-html to clean pasted text for draftJS editor.

Lets say result might be text string like this

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

Now i need to replace " with « or » depends on conditions. How should i do that. I tried to figure out if i can do it with draftJS ContentBlock methods, but it seems way too plicated. So i think it is easier to modify html string.

Share Improve this question asked May 26, 2017 at 8:26 LauriLauri 651 gold badge4 silver badges12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

You can do this with two regular expressions I guess:

    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);

  1. Create a replaceAll function. Because replace function will replace the only first occurrence.

    String.prototype.replaceAll = function(string, replace) {
    return this.split(string).join(replace);
    };
    
  2. Call the function like this.

    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);
    
发布评论

评论列表(0)

  1. 暂无评论