Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex match and get values from string

I've got a string of text which can have specific tags in it. Example: var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';

What I'm trying to do is do a regex match against the <pause #></pause> tag. For each tags found, in this case it's <pause 4></pause> and <pause 7></pause>. What I want is to grab the value 4 and 7, and the string length divided by for the string in between the <pause #>...</pause> tags.

What I have for now is not much. But I cant figure out how to grab all the cases, then loop through each one and grab the values I'm looking for.

My function for this looks like this for now, it's not much:

/**
* checkTags(string)
* Just check for tags, and add them
* to the proper arrays for drawing later on
* @return string
*/
function checkTags(string) {

    // Regular expresions we will use
    var regex = {
        pause: /<pause (.*?)>(.*?)<\/pause>/g
    }

    var matchedPauses = string.match(regex.pause);

    // For each match
      // Grab the pause seconds <pause SECONDS>
      // Grab the length of the string divided by 2 "string.length/2" between the <pause></pause> tags
      // Push the values to "pauses" [seconds, string.length/2]

    // Remove the tags from the original string variable

    return string;


}

If anyone can explain my how I could do this I would be very thankful! :)

like image 591
Kaizokupuffball Avatar asked Sep 27 '26 17:09

Kaizokupuffball


1 Answers

match(/.../g) doesn't save subgroups, you're going to need exec or replace to do that. Here's an example of a replace-based helper function to get all matches:

function matchAll(re, str) {
  var matches = [];
  str.replace(re, function() {
    matches.push([...arguments]);
  });
  return matches;
}

var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';

var re = /<pause (\d+)>(.+?)<\/pause>/g;

console.log(matchAll(re, string))

Since you're removing tags anyways, you can also use replace directly.

like image 182
georg Avatar answered Sep 30 '26 06:09

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!