Skip to content
Advertisement

Regular expression to convert html class to attribute

Is there any way to use regular expression alone or with help of javascript to do the following

from

<div class="type-c red blue"> 

to

<div type="c" class="red blue"> 

Advertisement

Answer

This regular expression will match what you describe, regardless of the position of “type-xxx” in class attribute

/class="([^"]*)type-(w+)([^"]*)"/g

Combining with a string replace

let value = '<div class="type-a b">test</div><div class="a type-b">test 2</div>';
value.replace(/class="([^"]*)type-(w+)([^"]*)"/g, 'type="$2" class="$1$3"');

this will yield the result

<div type="a" class="b">test</div><div type="b" class="a">test 2</div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement