0

how can I extract values ​​from a string that is highly variable:

this is string:

let texto='The trip takes <span class="length">468 mi</span> and <span class="time">8:18 h</span>';

I want to extract the values ​​the numbers that are the ones that always vary

  • 468 mi
  • 8:18 h

variant:

  • 1468 mi
  • 28:18 h

I've been working with substring but I don't have favorable results

console.log(texto.substring(15,5));
1
  • This string looks like it's comming from HTML document therfore you could cimply get the innerHTML value of each span using something like document.querySelector('span.length').innerHTML Commented Dec 15, 2020 at 1:01

1 Answer 1

3

This would be a great use case for regular expressions! Consider the following regexes for first matching for miles and then matching for hours.

let texto='The trip takes <span class="length">468 mi</span> and <span class="time">8:18 h</span>';

const miles = texto.match(/\d+ mi/);
const hours = texto.match(/\d{1,2}:\d\d h/);

console.log(miles[0])
console.log(hours[0]);

Now since your texto variable appers to be HTML, you might not need regex since the HTML might be structured enough to parse by accessing the DOM.

const miles = document.querySelector('.length').innerText;
const hours = document.querySelector('.time').innerText;

console.log(miles);

console.log(hours);
The trip takes <span class="length">468 mi</span> and <span class="time">8:18 h</span>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.