简体   繁体   中英

Removing html attribute from String?

I have a html string which looks like this:

<div id="demo_..." class="menu">

The html code is available as a string. Now I would like to remove all id attributes which start with demo_. The result should be this:

<div class="menu">

I know that it should work with regular expressions. But I am a little bit struggling with the special characters. How should the regular expression look like so that all strings with this format can be replaced by an empty string?

You can use substring attribute selector

[att^=val] Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.

[att$=val] Represents an element with the att attribute whose value ends with the suffix "val". If "val" is the empty string then the selector does not represent anything.

[att*=val] Represents an element with the att attribute whose value contains at least one instance of the substring "val". If "val" is the empty string then the selector does not represent anything.

For your case you could use

document.querySelectorAll('[id^="demo_"]')

or

document.querySelectorAll('[id*="demo_"]')

The result would be an array of HTMLElement with id attribute whose value begins with the prefix demo_ or contains demo_ if using * instead of ^ . From there you could remove each HTMLElement id att using removeAttribute() Method. More reading fromhere .

document.querySelectorAll('[id^="demo_"]')
 .forEach(element => element.removeAttribute('id'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM