从包含大量数据的文本区域中删除某些文本

Deleting certain text from textarea with large amounts of data

本文关键字:文本 删除 区域 数据 包含大      更新时间:2023-09-26

我使用HTML和Javascript制作了一个基本的XML格式化程序。我想在此添加一个删除功能。基本上,我希望能够删除一个条目,但不会清除或破坏任何其他数据。

<contact
<!--John Doe-->
 first_name="John"
 last_name="Doe"
 contact_type="sip"
 account_id="104"
 subscribe_to="sip:104@10.10.1.24"
 has_voicemail="1"
 can_monitor="1"
>
<numbers>
 <number dial="1064" dial_prefix="" label="Extension" />
 <number dial="555-0123" dial_prefix="718" label="Work Line" primary="1" />

我的想法是找到包含John Doe的联系人标签,并从<contact删除到</numbers>

不能使用`indexOf()通过包含某些信息来删除此组。

对于上下文:我在plunkr中添加了一个演示。这会获取表单数据并将其导出到文本区域

http://run.plnkr.co/plunks/b9QKZ7KZP0IlcyeCTTc9/

我认为您可以尝试其他方法。

  1. 创建一些Javascript对象来保存数据
  2. 将对象呈现到该文本区域
  3. 添加/删除数据时,请先操作对象,然后重新显示

代码看起来像

//Contact list.
var contacts = [];
// Contact class.
function Contact() {
    ...
    this.name = "";
    this.numbers = [];// numbers
    ...
}
Contact.prototype.toString = function(){
    return "<contact name='"" + this.name + ...;
};
// Add new Contact
function addContact(params) {
    var contact = new Contact();
    // set properties
    // contact.name = name;
    contacts.push(contact);
    showContacts();
}
// Add new Contact
function deleteContact(name) {
    for (var i = contacts.length-1; i >= 0; i--) {
        if (contacts[i].name == name) {
            contacts.splice(i, 1);
            return;
        }
    }
}
// present contacts
function showContacts(){
    var text = "";
    for(var c in contacts){
        text += c.toString();
    }
    textarea.value = text;
}
// other functions like addNumber etc.

代码会变得有点复杂,但会更加清晰和灵活。