Jquery——从HTML中删除一个字符,但保留HTML标记不变

时间:2022-08-27 12:32:35

I'm trying to build a simple CMS where users can write anything in contenteditable div. When they're saving their work I want to remove specific characters from the text they putted i.e.:

我正在尝试构建一个简单的CMS,用户可以在contenteditable div中编写任何内容。

The text is:

文字是:

<ul>
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
</ul>

I know how to remove the comma with jquery .text(), but it just gives me a plain text without HTML tags. The problem is that I don't know if or how many HTML tags will be at the end of a sentence where the comma should be removed.

我知道如何使用jquery .text()删除逗号,但它只提供了一个没有HTML标记的纯文本。问题是,我不知道句子末尾是否应该删除逗号,或者应该删除多少个HTML标记。

Is there any other way to remove this comma without touching a HTML tags? So after saving the work the text would stay styled as it should be but without comma at the end of LI element?

有没有其他方法可以在不接触HTML标签的情况下删除这个逗号?所以在保存工作之后,文本将保持其应有的样式,但是在LI元素的末尾没有逗号?

Simple fiddle: jsfiddle

简单的小提琴:jsfiddle

4 个解决方案

#1


2  

This is probably not the cleanest way of doing it, but it works in your test cases. Might want to run an rtrim method on the text to remove whitespace. And would fail if someone added an empty element after the ,.

这可能不是最干净的方法,但是它在您的测试用例中是有效的。可能需要在文本上运行rtrim方法来删除空格。如果在,之后添加一个空元素,则会失败。

$(function(){
    
    function getLastTextNode(x){
        var last = x.last();
        var temp = last.contents();  //get elements inside the last node
        var lTemp = temp.last(); //Get the contents inside the last node
        if (temp.length>1 || lTemp[0].nodeType===1) {  //if the last node has multiple nodes or the last node is an element, than keep on walking the tree
            getLastTextNode(lTemp);  
        } else {  //we have a textNode
            var val = lTemp[0].nodeValue; //get the string
            lTemp[0].nodeValue = val.substr(0,val.length-1);  //chop off the comma
        }
    }
    
    $('#remCom').on('click', function(){
        $('#CorrectHTML').html('');
        $('li').each(function(){
            var li = $(this);
            //see if the last character is a comma.
            if (li.text().substr(-1)===",") {                
                getLastTextNode(li.contents());
            }
        });    
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="HTMLtoBeChanged">
    <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
    <li>Here is no comma at the end, so it should <b>stay as it is</b></li>
    <li>And here the comma should <b>dissapear also,</b></li>
</ul>
<button id="remCom">Remove commas</button>
<ul id="CorrectHTML"></ul>

Or you can do it this way. The issue with the html() way is if you added event handlers to any of the elements inside, they will be destroyed.

或者你可以这样做。html()方法的问题是,如果向内部的任何元素添加事件处理程序,它们将被销毁。

$(function() {
    $('#remCom').on('click', function() { 
        $('#CorrectHTML').html('');
        $('li').each(function() {
            var li = $(this);
            //see if the last character is a comma.
            if (li.text().trim().substr(-1) === ",") {
                var html = li.html(); //grab the html
                var pos = html.lastIndexOf(',');  //find the last comma
                html = html.substring(0, pos) + html.substring(pos + 1);  //remove it
                li.html(html);  //set back updated html
            }
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="HTMLtoBeChanged">
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
  <li>Here is no comma at the end, so it should <b>stay as it is</b></li>
  <li>And here the comma should <b>dissapear also,</b></li>
</ul>
<button id="remCom">Remove commas</button>
<ul id="CorrectHTML"></ul>

#2


2  

General approach to solve the problem

解决问题的一般方法

  • Get the .text(), check if the last character is a comma
  • 获取.text(),检查最后一个字符是否是逗号
  • If it is, remove the last comma from the .html() with lastindexof
  • 如果是,使用lastindexof从.html()中删除最后一个逗号
  • Apply this string to the element
  • 将此字符串应用到元素

#3


1  

Here's a fiddle to a working example:

下面是一个有用的例子:

http://jsfiddle.net/ooehwkqy/6/

http://jsfiddle.net/ooehwkqy/6/

$(function(){
    $('#remCom').on('click', function(){
        $('#CorrectHTML').html('');
        $('li').each(function(){
            var thisText = $(this).html().trim();
            var result = /[^,]*$/.exec(thisText)[0];
            result = result.replace(/(<([^>]+)>)/ig, "");
            if(!result){
                thisText = thisText.replace(/,([^,]*)$/,'$1');
            }
            $('#CorrectHTML').append('<li>' + thisText + '</li>');
        });    
    });
});

Basically, use regex to remove any characters that you don't want and replace them with nothing.

基本上,使用regex删除任何您不想要的字符,并将它们替换为零。

EDIT

编辑

This accounts for commas that also are scattered before and after formatting tags and only removes the commas at the ends.

这表示在格式化标记前后也分散的逗号,并且只在末尾删除逗号。

#4


1  

Try this

试试这个

$(function() {
    var $ul=$("ul"), text = $ul.text().split(" "), last = $.trim(text[text.length-1]);
    if (last && last.lastIndexOf(",")==last.length-1) {
      $ul.replaceWith(
        $ul[0].outerHTML.replace(last,last.substring(0,last.length-1))
      );
    }                      
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
</ul>

To run over all LIs do this:

对所有LIs这样做:

$(function() {
  $("ul li").each(function() {
    var $li = $(this),
      text = $li.text().split(" "),
      last = $.trim(text[text.length - 1]);
    if (last && last.lastIndexOf(",") == last.length - 1) {
      $li.replaceWith(
        $li[0].outerHTML.replace(last, last.substring(0, last.length - 1))
      );
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
</ul>

#1


2  

This is probably not the cleanest way of doing it, but it works in your test cases. Might want to run an rtrim method on the text to remove whitespace. And would fail if someone added an empty element after the ,.

这可能不是最干净的方法,但是它在您的测试用例中是有效的。可能需要在文本上运行rtrim方法来删除空格。如果在,之后添加一个空元素,则会失败。

$(function(){
    
    function getLastTextNode(x){
        var last = x.last();
        var temp = last.contents();  //get elements inside the last node
        var lTemp = temp.last(); //Get the contents inside the last node
        if (temp.length>1 || lTemp[0].nodeType===1) {  //if the last node has multiple nodes or the last node is an element, than keep on walking the tree
            getLastTextNode(lTemp);  
        } else {  //we have a textNode
            var val = lTemp[0].nodeValue; //get the string
            lTemp[0].nodeValue = val.substr(0,val.length-1);  //chop off the comma
        }
    }
    
    $('#remCom').on('click', function(){
        $('#CorrectHTML').html('');
        $('li').each(function(){
            var li = $(this);
            //see if the last character is a comma.
            if (li.text().substr(-1)===",") {                
                getLastTextNode(li.contents());
            }
        });    
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="HTMLtoBeChanged">
    <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
    <li>Here is no comma at the end, so it should <b>stay as it is</b></li>
    <li>And here the comma should <b>dissapear also,</b></li>
</ul>
<button id="remCom">Remove commas</button>
<ul id="CorrectHTML"></ul>

Or you can do it this way. The issue with the html() way is if you added event handlers to any of the elements inside, they will be destroyed.

或者你可以这样做。html()方法的问题是,如果向内部的任何元素添加事件处理程序,它们将被销毁。

$(function() {
    $('#remCom').on('click', function() { 
        $('#CorrectHTML').html('');
        $('li').each(function() {
            var li = $(this);
            //see if the last character is a comma.
            if (li.text().trim().substr(-1) === ",") {
                var html = li.html(); //grab the html
                var pos = html.lastIndexOf(',');  //find the last comma
                html = html.substring(0, pos) + html.substring(pos + 1);  //remove it
                li.html(html);  //set back updated html
            }
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="HTMLtoBeChanged">
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
  <li>Here is no comma at the end, so it should <b>stay as it is</b></li>
  <li>And here the comma should <b>dissapear also,</b></li>
</ul>
<button id="remCom">Remove commas</button>
<ul id="CorrectHTML"></ul>

#2


2  

General approach to solve the problem

解决问题的一般方法

  • Get the .text(), check if the last character is a comma
  • 获取.text(),检查最后一个字符是否是逗号
  • If it is, remove the last comma from the .html() with lastindexof
  • 如果是,使用lastindexof从.html()中删除最后一个逗号
  • Apply this string to the element
  • 将此字符串应用到元素

#3


1  

Here's a fiddle to a working example:

下面是一个有用的例子:

http://jsfiddle.net/ooehwkqy/6/

http://jsfiddle.net/ooehwkqy/6/

$(function(){
    $('#remCom').on('click', function(){
        $('#CorrectHTML').html('');
        $('li').each(function(){
            var thisText = $(this).html().trim();
            var result = /[^,]*$/.exec(thisText)[0];
            result = result.replace(/(<([^>]+)>)/ig, "");
            if(!result){
                thisText = thisText.replace(/,([^,]*)$/,'$1');
            }
            $('#CorrectHTML').append('<li>' + thisText + '</li>');
        });    
    });
});

Basically, use regex to remove any characters that you don't want and replace them with nothing.

基本上,使用regex删除任何您不想要的字符,并将它们替换为零。

EDIT

编辑

This accounts for commas that also are scattered before and after formatting tags and only removes the commas at the ends.

这表示在格式化标记前后也分散的逗号,并且只在末尾删除逗号。

#4


1  

Try this

试试这个

$(function() {
    var $ul=$("ul"), text = $ul.text().split(" "), last = $.trim(text[text.length-1]);
    if (last && last.lastIndexOf(",")==last.length-1) {
      $ul.replaceWith(
        $ul[0].outerHTML.replace(last,last.substring(0,last.length-1))
      );
    }                      
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
</ul>

To run over all LIs do this:

对所有LIs这样做:

$(function() {
  $("ul li").each(function() {
    var $li = $(this),
      text = $li.text().split(" "),
      last = $.trim(text[text.length - 1]);
    if (last && last.lastIndexOf(",") == last.length - 1) {
      $li.replaceWith(
        $li[0].outerHTML.replace(last, last.substring(0, last.length - 1))
      );
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
  <li>This is the text inserted by <b>user</b> and styled by him - there should be no comma at the end of a <b><i><u>LI element,</u></i></b></li>
</ul>