dennismonsewicz
dennismonsewicz

Reputation: 25542

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. I have to convert the value of the textarea to HTML, then I want to search the HTML for words... but its not working...

any ideas?

Upvotes: 1

Views: 1716

Answers (2)

Daniel A. White
Daniel A. White

Reputation: 190925

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

should be

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

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532435

The value of the textarea is aalready a string. The html method doesn't work the way you think it does. It should be a simple matter of removing the bits where you are attempting to use 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> 

Upvotes: 0

Related Questions