簡體   English   中英

如何在JavaScript中使用正則表達式,匹配項和執行項從文本中刪除重復項

[英]How to remove duplicates from text using regex, match and exec in javascript

我的JavaScript知識是有限的。 我使用此代碼:

var myString = $("#builder-area-center-frame-content").html();
var pattern = /{{(.*?)}}/g;
var match;

while ((match = pattern.exec(myString)) !== null ){
    $("#sim-edit-variable-replace").show();
    $("#sim-edit-variable-replace select[name=variable_element]").append('<option value="'+ match[0] +'">'+ match[1] +'</option>');
}

“ myString”是我的div#builder-area-center-frame-content的容器,在我的div中有類似{{FOO}}或{{TOTO}}等元素,等等。

我有一個帶有選擇的表單,在循環中,我為找到的每個{{XXX}}創建選項屬性。 但是,例如,如果有2 {{FOO}},則選項屬性將重復兩次。 像這個例子:

<select class="form-control" name="variable_element"><option value="{{FOO}}">FOO</option><option value="{{FOO}}">FOO</option><option value="{{toto}}">toto</option></select>

如何刪除重復的{{FOO}}只保留一個?

對不起,我的英語不好,我希望你能理解我想做什么?

編輯:我嘗試了您的代碼,但是我渲染'let'時出現很多錯誤。 我正在使用NetBeans。

function variable_replace() {

  let str = $("#builder-area-center-frame-content").html();
  let collection = str.match(/{{[aA-zZ]+}}/g).filter((item, index, self) => index === self.indexOf(item));

  if (collection.length > 0) {
    $('#sim-edit-variable-replace').show();
    let elem = $('#sim-edit-variable-replace select[name=variable_element]');
    for (let item of collection) {
    elem.append('<option value="${item.replace(/[{}]/g, '')}">${item}</option>');
    }
  }
}
variable_replace();

如果可以獲取元素內容的字符串值,則可以使用正則表達式來匹配輸入,並使用Array#filter檢查是否存在重復項。

 let str = '{{TODO}}{{FOO}}{{FOO}} {{TODO}}'; let collection = str.match(/{{[aA-zZ]+}}/g).filter((item, index, self) => index === self.indexOf(item)); console.log(collection); 

編輯:您可以將for循環替換為while循環,並遍歷數組中的所有項目以將新選項附加到選擇元素。

if (collection.length > 0) {
    $('#sim-edit-variable-replace').show();

    let elem = $('#sim-edit-variable-replace select[name=variable_element]');
    for (let item of collection) {
        elem.append(`<option value="${item.replace(/[{}]/g, '')}">${item}</option>`);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM