imvain2
imvain2

Reputation: 15857

Javascript regex For Removing height/width from style

Using HTMLFilter addrules in CKEDITOR, I'm trying to remove the height/width from the STYLE of plain text.

They don't return the actual object just plain text style so I really can't use jQuery or other DOM manipulation tools.

I have the below regex code that successfully removes HEIGHT and WIDTH but still leaves the actual dimensions.

I'm new to regular expressions so I'm sure it's something rather simple. Just not sure what.

Thank you.

var str = "width:100px;height:200px;float:left;";
var regex = /(height|width):(?=(.*?);)/gi;
console.log(str.replace(regex,""));

Upvotes: 2

Views: 1548

Answers (4)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38542

A non-regex solution with javascript built-ins methods to remove the height/width from the STYLE of plain text.

function isNotWidthHeight(style) {
  return style.toLowerCase().indexOf("width") === -1 && style.toLowerCase().indexOf("height") === -1 && style;
}

var str = "margin:0 auto;width:100px;height:200px;float:left;";
var array = str.split(';').filter(isNotWidthHeight);
console.log(array.join(';'));

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627219

You used a lookahead, and it is a non-consuming pattern, i.e. the text it matches does not become part of the whole match value. Thus, it does not get removed

Use a pattern like

/(?:height|width):[^;]*;/gi

See the regex demo.

Details

See JS demo:

var str = "width:100px;height:200px;float:left;";
var regex = /(?:height|width):[^;]*;/gi;
console.log(str.replace(regex,""));

Upvotes: 2

GenericUser
GenericUser

Reputation: 3229

Pretty close, you just need an extra group and something to wait until either ; or word boundary, \b. This will grab any setting including calc or whatever settings can follow until the ; or end of inline style.

var str = "width:100px;height:200px;float:left;";
var str2 = "width:calc(100vh - 20px);height:100%;float:left;";

var regex = /((width|height):[\s\S]+?;|\b)/gi;
console.log(str.replace(regex,""));
console.log(str2.replace(regex,""));

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You need to capture the values too. .*? instead of (?=(.*?);) will be enough.

var str = "width:100px;height:200px;float:left;";
var regex = /(height|width):.*?;/gi;
console.log(str.replace(regex,""));

Upvotes: 0

Related Questions