如何从字符串javscript返回id

时间:2018-06-23 23:46:37

标签: javascript

var str = '<input style="background-image: url(&quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTR2VDVmOQ8AKjqY1bMHgCGYXhFchnAg6omJGcBXEZRtNoXYK2dMsaMt1qtD9/3p40x5yS9tHI6o1wuz1lrVzpWXLDWTg3pz/0CQnd2Jos49xUAAAAASUVORK5CYII=&quot;); background-repeat: no-repeat; background-attachment: scroll; background-position: right center; cursor: auto; outline: 1px solid blue;" autocomplete="email" class="mat-input-element mat-form-field-autofill-control mat-input-server ng-untouched ng-pristine ng-invalid" matinput="" name="email" required="" id="mat-input-112621" placeholder="E-mail Address" aria-invalid="false" aria-required="true" value="" type="email">'

我如何从该字符串返回 id =“ mat-input-112621” ,所有html代码都是字符串,因此仅尝试返回ID。

2 个答案:

答案 0 :(得分:2)

您可以创建一个元素,将字符串插入其中,然后要求第一个孩子的id

请注意,如果该字符串包含多个HTML元素(同时还有一个id),则需要相应地调整此解决方案。

var str = '<input style="background-image: url(&quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTR2VDVmOQ8AKjqY1bMHgCGYXhFchnAg6omJGcBXEZRtNoXYK2dMsaMt1qtD9/3p40x5yS9tHI6o1wuz1lrVzpWXLDWTg3pz/0CQnd2Jos49xUAAAAASUVORK5CYII=&quot;); background-repeat: no-repeat; background-attachment: scroll; background-position: right center; cursor: auto; outline: 1px solid blue;" autocomplete="email" class="mat-input-element mat-form-field-autofill-control mat-input-server ng-untouched ng-pristine ng-invalid" matinput="" name="email" required="" id="mat-input-112621" placeholder="E-mail Address" aria-invalid="false" aria-required="true" value="" type="email">'

var el = document.createElement('div');
el.innerHTML = str;
console.log(el.children[0].id);

答案 1 :(得分:0)

您可以使用一个简单的正则表达式。

如果保证在那里,那么可以这样做:

var str = '<input style="background-image: url(&quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTR2VDVmOQ8AKjqY1bMHgCGYXhFchnAg6omJGcBXEZRtNoXYK2dMsaMt1qtD9/3p40x5yS9tHI6o1wuz1lrVzpWXLDWTg3pz/0CQnd2Jos49xUAAAAASUVORK5CYII=&quot;); background-repeat: no-repeat; background-attachment: scroll; background-position: right center; cursor: auto; outline: 1px solid blue;" autocomplete="email" class="mat-input-element mat-form-field-autofill-control mat-input-server ng-untouched ng-pristine ng-invalid" matinput="" name="email" required="" id="mat-input-112621" placeholder="E-mail Address" aria-invalid="false" aria-required="true" value="" type="email">';

console.log(str.match(/\b\id="([^"]+)"/)[1])

否则,您可能必须在进行第一组比赛之前检查比赛是否存在。