Faizan Saiyed
Faizan Saiyed

Reputation: 852

JavaScript - Select string between specific word and next specific character on custom condition

I have a very long CSS code in a variable and I want to find the last matching condition in that. My code is:

var str = 'body { background: #fff; } .customClass{ font-size: 12px; } .anotherClass { color: #292929 } body { color : #fff }';
var str2 = str.substring(str.lastIndexOf("body {") + 1, str.lastIndexOf("}"));
console.log(str2);

Here, I've shortened str for better understanding. In my case, it's around 100-200 lines minimum.

Now I only want the last body { anything here } substring. In above Eg. I want body {color: #fff } and not the first or any other occurrence of the body tag in the string. I know multiple body styling is not good code, but right now this code is dependent on a third party plugin. How can I do that?

Fiddle

Upvotes: 1

Views: 48

Answers (3)

chinmayan
chinmayan

Reputation: 1384

You just have to make a small change in your str2

var str2 = str.substring(str.lastIndexOf("body"));

This will result the str2 as body {color: #fff } and if you need only the style part, add the following line too.

var styleStr = str2.substring(str2.indexOf('{')+1, str2.indexOf('}'));

Now it will result a string like color : #fff

Upvotes: 0

Nishant Dixit
Nishant Dixit

Reputation: 5522

Try this :)

var str = 'body { background: #fff; } .customClass{ font-size: 12px; } .anotherClass { color: #292929 } body { color : #fff } body{cool}';
var regex = /body\s+\{([^}]+)/g;
var temp;
var resultArray = [];
while ((temp = regex.exec(str)) != null)  
{  
resultArray.push(temp[1]);
} 
console.log(resultArray);

Upvotes: 1

xianshenglu
xianshenglu

Reputation: 5329

you are almost right with a little confusion about substring

var str = 'body { background: #fff; } .customClass{ font-size: 12px; } .anotherClass { color: #292929 } body { color : #fff }';
var str2 = str.substring(str.lastIndexOf("body {"), str.lastIndexOf("}") + 1);
console.log(str2);

Upvotes: 1

Related Questions