Search code examples
imacros

how to extract only first two characters with imacro?


So the HTML code is :

    <span class="countdown">
    01:22
    </span>

The imacro code to extract the text (01:22) is :

TAG POS=1 TYPE=SPAN ATTR=CLASS:"countdown" EXTRACT=TXT

I want to extract only the first two characters and not the whole text, in the example i posted , the extracted TEXT would be "01" and not "01:22"


Solution

  • You will need to use the imacro EVAL method and use a little bit of javascript and regex to break up the string and assign it to another variable so that you get the first 2 characters. Below is the solution:

    TAG POS=1 TYPE=SPAN ATTR=CLASS:"countdown" EXTRACT=TXT
    SET !VAR1 EVAL("var x=\"{{!EXTRACT}}\"; x=x.match(/^.{2}/).join(''); x;")
    PROMPT {{!VAR1}}
    

    Enjoy! If this was helpful, please mark as such, thanks!

    Edit Here's a slightly better method, using the javascript split function. This will allow you to specify the 1st part (01) or the 2nd part (22) of 01:22

    TAG POS=1 TYPE=SPAN ATTR=CLASS:"countdown" EXTRACT=TXT
    ' Below line will assign the first part before colon (01) to VAR1
    SET !VAR1 EVAL("var x=\"{{!EXTRACT}}\"; y=x.join(':'); y[0];")
    ' Below line will assign the first part before colon (01) to VAR2
    SET !VAR2 EVAL("var x=\"{{!EXTRACT}}\"; x=x.join(':'); y[1];")
    PROMPT {{!VAR1}}
    

    Answer updated due to recent comment/question to my answer.