jQuery变量设置为正则表达式

jQuery variable-setting for regex

本文关键字:正则表达式 设置 变量 jQuery      更新时间:2023-09-26

按预期记录10个textarea元素中的每个元素的值:

$('.container').each(function() {
    var textA = $('textarea', this).val();
    console.log(textA)
});

这个正则表达式在控制台工作得很好:

"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"]

但是当我尝试这个时:

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

我得到Uncaught TypeError: Cannot read property 'match' of undefined

为什么是undefined ?是不是因为进入matchType没有正确申报?如有,我应如何申报,以便"看到"?

要回答这个问题:您需要检查textarea是否存在于.container中。您可以使用.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>