Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

javascript - How to get substring of font family using regex in JS

I am trying to get the font family from a string representing parts of html. Font-family can be any font, which is why I was thinking of using a regex. String can also be x amount of characters. An example input would be:

'<body id="foo" class="bar"><span style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas">Example Text</span></body>'

The ideal result would be "Consolas". However I'm not that good with regex and not able to come up with an appropriate regex.

Data comes in as string representation of element

SOLUTION: Thanks to terrymorse(comments) and Gerardo Cabrera(accepted answer)! I was unaware of how to convert html string into an element. Was able to pull out the font-family based on their feedback

question from:https://stackoverflow.com/questions/65909666/how-to-get-substring-of-font-family-using-regex-in-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like everyone says, it is not a good idea to use regex to try and parse HTML. Just use the DOM like this:

// Like the user   terrymorse   did
let div = document.createElement('div'); 
div.innerHTML = '<body id="foo" class="bar"><span style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas">Example Text</span></body>';

let children = div.children;

console.log(children[0].style.fontFamily);

You could also use split and array functions in order to find the property like this, but the DOM option is way better.

var s = '<body id="foo" class="bar"><span style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas">Example Text</span></body>';

var x = s.split(";");
var y = x.filter(e => e.includes("font-family"))[0].split('"')[0];
 
var result = y.replace("font-family: ", "");

console.log(result)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...