scharfmn
scharfmn

Reputation: 3661

jQuery variable-setting for regex

This logs the values of each of 10 textarea elements as expected:

$('.container').each(function() {

    var textA = $('textarea', this).val();
    console.log(textA)

});

This regex works fine in the console:

"https://hi.com/hey junk nothing https://hi.com/there".match(/https:\/\/hi\.com\/[A-Za-z_]{1,15}/ig);

I get back: ["https://hi.com/hey", "https://hi.com/there"]

But when I try this:

$('.container').each(function() {

    var textA = $('textarea', this).val();
    var matches = textA.match(/https:\/\/hi\.com\/[A-Za-z_]{1,15}/ig);
    console.log(matches)

});

I get Uncaught TypeError: Cannot read property 'match' of undefined

Why undefined? Is it because the Type of what is coming in to match hasn't been declared properly? If so, how should I declare so that it can be 'seen'?

Upvotes: 1

Views: 53

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

To answer the question: you need to check if textarea is present in the .container. You can check it with .length > 0:

$('.container').each(function() {

    var textArea = $('textarea', this);    // Changed here
    if (textArea.length > 0) {             // and here
        var textA = textArea.val();
        var matches = textA.match(/https:\/\/hi\.com\/[A-Za-z_]{1,15}/ig);
        console.log(matches);
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<textarea name="mytextarea" id="" cols="30" rows="10">
https://hi.com/new-url
More
  lines
      https://hi.com/last-url
    </textarea>        
</div>

<div class="container">
  Empty one with no textarea
</div>

Upvotes: 1

Related Questions