0

I get size of the PDF files within the name of the the file on page

console.log($(opt).text() + " selected")

opt has the value such as abcs{853269}

I get the value using regular expression:

var curSize = $(opt).text();
console.log(curSize + "current Size");

var counter = 0;
var result = curSize.match(/{(.*?)}/);
console.log('sizee' + result);

The console result is {853269},853269

I don't know why I am getting two results, I thought regex will only return one.

Now I have a for loop to calculate all the values that are selected and give it back to me as one big sum:

if ( result !=null){
    for(var i=0; i< result.length; i++){
        counter += result[i];
        document.getElementById("textarea").value += result[i];
    }
    console.log(counter + "Counter");
}

...but it's crashing.

1
  • result[0] is the whole match, and the rest of the elements are the contents of the capturing groups. result[1] is what you want. Commented May 15, 2016 at 22:08

2 Answers 2

1

If you take a look at the regex documentation you can see it returns:

An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.

Your first item in the array is the entire expression that was matched by the regex. The second item that you see is the value extracted from the match group (your parenthesis). Use the second value directly.

var result = curSize.match(/{(.*?)}/);

var extractedText = undefined;
if(result) {
    extractedText = result[1];
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here's what MDN says about String.prototype.match (page):

The match() method retrieves the matches when matching a string against a regular expression.

With your current regular expression, there's an item (in the array returned from String.match) for a match to the entire regular expression. That explains the first result ({853269}).

The second item in the resulting array (853269), is coming from the group that you defined in your regular expression.

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.