简体   繁体   English

用span类替换HTML字符串中的一些innerTexts并发布回DOM

[英]Replacing some innerTexts in a HTML string with span class and publishing back to DOM

I have a HTML string ( not DOM element ) like : 我有一个HTML字符串(不是DOM元素),如:

  <p>This is a sample dataa<p>
  <img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img>

I need to append a <span class="spellerror"></span> to the words that have problem and that too only the Textual contents need to be checked and appended . 我需要将<span class="spellerror"></span>附加到有问题的单词上,并且只需要检查和追加文本内容。

  <p>This is a sample dataa<p>
  <img src="Randomz" alt="Randomz Image"><span class="spellerror"> Randomz </span> is the name of the image</img>  

My problem is that this is a mix of HTML and regex . 我的问题是这是HTML和正则表达式的混合。 Is it possible: 可能吗:

  1. To make this some kind of a DOM element and then work on it ? 为了使它成为某种DOM元素然后继续工作?
  2. Or is there a regex way to achieve this. 或者有一种正则表达方式来实现这一目标。

I dont want to touch the attributes and if I modify Text contents , how do I publish it back ...because I need some HTML inserted there . 我不想触摸属性,如果我修改文本内容,我该如何发布它...因为我需要插入一些HTML。

Use some form of templating: 使用某种形式的模板:

String.prototype.template = String.prototype.template ||
        function (){
            var  args = Array.prototype.slice.call(arguments)
                ,str = this
            ;
            function replacer(a){
                var aa = Number(a.substr(1))-1;
                return args[aa];
            }
            return  str.replace(/(\$\d+)/gm,replacer);
 };
 var thestring = [ '<p>This is a sample dataa</p><img src="Randomz"'
                  ,' alt="Randomz Image">$1Randomz$2 '
                  ,'is the name of the image</img>'].join('')
    ,nwString = theString.template('<span class="spellerror">','</span>');

I dont love this solution, but it works: 我不喜欢这个解决方案,但它有效:

'<img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img>'
    .match(/<[^>]+>|[^<]+|<\/[^>]+>/g)
    .map(function (text, index) {
        if (index === 1) {
            return text.replace(/(Randomz)/, '<span class="spellerror">$1</span>');
        } else {
            return text;
        }
    })
    .join('');

The regex splits into opening tag, innerText, closing tag. 正则表达式分为开始标记,innerText,结束标记。 Then iterates on all members, if its the innerText, it replaces with desired text Then joins. 然后迭代所有成员,如果是innerText,它将替换为所需的文本然后加入。

Im stil trying to think of something less round-about but thats all i got 我试图想到一些不那么圆的东西,但这就是我所得到的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM