Tabares
Tabares

Reputation: 4335

How to keep values and remove the others (attributes html string) on a regular expression?

I want to know if is possible keep certain values and remove other with a regular expersion.

I have this code:

var str = '<td class="sky" data-toggle="up" id="heaven" > Link to heaven </td>';

var res = str.replace(/(data-toggle=")([a-zA-Z0-9:;\.\s\(\)\-\,]*)(")/gi, '');

console.log(res);

My result is the follow:

<td class="sky"  id="heaven" > Link to heaven </td>

I want to expect the result like this (inverse):

<td data-toggle="up" > Link to heaven </td>

Upvotes: 0

Views: 236

Answers (2)

Kerwin
Kerwin

Reputation: 1212

see

var str = '<td class="sky" data-toggle="up" id="heaven" > Link to heaven </td>';

var res = str.replace(/(<\w+)(\s*[\w-]+="[^"]+")*(\s*data-toggle="[^"]+")(\s*[\w-]+="[^"]+")*(\s*>)/g, '$1$3$5');

console.log(res);

Upvotes: 1

Ray Chen
Ray Chen

Reputation: 182

Then, your requirement here is to replace all existing attribute settings of a TD element with the new attribute setting data-toggle="up", correct? If so, maybe you can use the following regular expressions.
Find : <td .+?>(.+)</td>
Replace : <td data-toggle="up" >\1</td>

Upvotes: 0

Related Questions