简体   繁体   English

jQuery:使用正则表达式在textarea值中搜索单词

[英]jQuery: Searching textarea value for words using regex

I have the following code: 我有以下代码:

<script type="text/javascript">
    $(function(){
        var txt = new Array();
        var count = 0;
        $('textarea[id*="page_parts_attributes_"]').each(function(){
            var html = $(this).html($(this).val());
            var matches = $(html).match(/\b/g)
            if(matches) {
                txt[count] = jQuery.trim(matches).length / 2
                count++;
            }
        });
        var final_count = eval(txt.join('+'));
        console.log(Math.floor(final_count));
    })
</script>

I am basically trying to search the textarea for words. 我基本上是想在textarea中搜索单词。 I have to convert the value of the textarea to HTML, then I want to search the HTML for words... but its not working... 我必须将textarea的值转换为HTML,然后我要在HTML中搜索单词...但是它不起作用...

any ideas? 有任何想法吗?

var html = $(this).html($(this).val());
var matches = $(html).match(/\b/g)

should be 应该

var matches = $(this).val().match(/\b/g);

The value of the textarea is aalready a string. textarea的值已经是一个字符串。 The html method doesn't work the way you think it does. html方法无法按您认为的方式工作。 It should be a simple matter of removing the bits where you are attempting to use html . 删除尝试使用html的位应该很简单。

<script type="text/javascript">  
    $(function(){  
        var txt = new Array();  
        var count = 0;  
        $('textarea[id*="page_parts_attributes_"]').each(function(){  
            var text = $(this).val();  
            var matches = text.match(/\b/g)  
            if(matches) {  
                txt[count] = jQuery.trim(matches).length / 2  
                count++;  
            }  
        });  
        var final_count = eval(txt.join('+'));  
        console.log(Math.floor(final_count));  
    })  
</script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM