1

I have a text box with ID test. I'd like to log each word within the text box with each.

$('#test').val().each(function(index) {
    console.log( index + ": " + $(this).text());
});

How would you do this? I'm aware mine won't work because each looks for actual elements.

3 Answers 3

4
$.each($('#test').val().split(/[ \t]+/), function(index, word) {
    console.log( index + ": " + word);
});
5
  • Thanks Maurice. Can you explain the use of split? Why did you use /[ \t]+/? Are you creating a regular expression to ignore those characters? Also, not sure if this matters, but it outputs 0 each time as an index without an associated value, then skips past it to 1 with an associated value.
    – user3871
    Jan 7, 2014 at 5:51
  • It's the separator between words. I assumed that words were separated by one or more whitespaces (space or tab). Jan 7, 2014 at 5:53
  • Okay thanks. Also, why is $.each required first? Why can't I use it as I have above?
    – user3871
    Jan 7, 2014 at 5:54
  • because .val() returns a string, and a string has no method .each Jan 7, 2014 at 5:55
  • 1
    You can use /\s+/ instead of /[ \t]+/ as \s includes tabs and spaces.
    – Mottie
    Jan 7, 2014 at 6:05
0

Try this,

$.each($('#test').text().split(/[ \t\n]+/),function(i,v){
    console.log( i + ": " + v);
});

FIDDLE

0

Try this

$.each($('#test').text().split(/[ \t\n]+/),function(i,v){
console.log( i + ": " + v);
});

DEMO

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.