Ad

Extracting A Piece Of Text From A String -- Javascript

- 1 answer

I'm using document.getElementById to get the innerHTML from a <div>. It will return something like this...

<span style="font-size: 18px; font-weight:bold; color: #545454;">Unit 1, Lesson 2: Ordering Large Numbers</span>

I want to extract the "Unit 1, Lesson 2" part from that string using Javascript. It won't always be "Unit 1, Lesson 2" though. It could be "Unit 10, Lesson 8" so using substring() seems to be out.

Desired Outcome...

<span style="font-size: 18px; font-weight:bold; color: #545454;">Unit 1, Lesson 5: Ordering Large Numbers</span> should yield "Unit 1, Lesson 5"

<span style="font-size: 18px; font-weight:bold; color: #545454;">Unit 11, Lesson 28: Ordering Large Numbers</span> should yield "Unit 11, Lesson 28"

I'm not good at all with Javascript, so if I'm missing a simple function to do this, please let me know what it is.

Edit: Alternatively, if there's a way to cut off everything after the ":", I could work with that as well.

Ad

Answer

You can use textContent which would return only text without html.

So if you have element:

<span id="test"><span style="font-size: 18px; font-weight:bold; color: #545454;">Unit 1, Lesson 2: Ordering Large Numbers</span></span>

You can get it's 'Unit 1, Lesson 2' part like this:

document.getElementById('test').textContent.split(":")[0];
Ad
source: stackoverflow.com
Ad