从字符串中提取特定值

时间:2019-12-12 12:06:27

标签: angular typescript

我正在实施提及系统,但是我无法直接获得ID。

我提到的用户ID在data-id =“ 1”分支中为String类型,如下面的代码所示。我打算得到这些ID的全部。

是否可以在此字符串中提取data-id中包含的所有值?

谢谢!

HTML

 <dx-html-editor (onValueChanged)="ment($event)">
    <dxi-mention
      valueExpr="id" 
      displayExpr="username"
      [dataSource]="allUsers">
     </dxi-mention>
 </dx-html-editor>

Component.ts

  ment(event) {
    if (event != null) {
      console.log(event.value)
    }
  }

STRING

 "<p><span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="Admin" data-id="1"><span contenteditable="false"><span>@</span>Admin</span></span>  testing <span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="Admin" data-id="1"><span contenteditable="false"><span>@</span>Admin</span></span>  new test <span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="Admin" data-id="1"><span contenteditable="false"><span>@</span>Admin</span></span>  new test <span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="Admin" data-id="1"><span contenteditable="false"><span>@</span>Admin</span></span>  newtest </p>"

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式/data-id=\"([0-9a-z]+)\"/gi从字符串中获取匹配项

类似的东西

const yourString = `<p><span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="Admin" data-id="1"><span contenteditable="false"><span>@</span>Admin</span></span>  testing <span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="Admin" data-id="1"><span contenteditable="false"><span>@</span>Admin</span></span>  new test <span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="Admin" data-id="1"><span contenteditable="false"><span>@</span>Admin</span></span>  new test <span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="Admin" data-id="1"><span contenteditable="false"><span>@</span>Admin</span></span>  newtest </p>`;

const dataIdRegx = /data-id=\"([0-9a-z]+)\"/gi;
const allDataIds = [];

match = dataIdRegx.exec(yourString);
while (match != null) {
  console.log(match[1]);
  allDataIds.push(match[1]);
  match = dataIdRegx.exec(youtString);
}