1

I have the following example where I am putting a limit on the characters entered in the Textarea:

var tlength = $(this).val().length;
    $(this).val($(this).val().substring(0, maxchars));
    var tlength = $(this).val().length;
    remain = maxchars - parseInt(tlength);
    $('#remain').text(remain);

where maxchars is the number of characters. How can I change this example to work with words, so instead of restricting chars, I restrict to a number of words.

http://jsfiddle.net/PzESw/106/

2
  • Like this -> jsfiddle.net/PzESw/110 Commented Mar 15, 2014 at 13:26
  • @adeneo My previous example took care of paste scenarios for chars. I want them for words too. So basically the same example working as-is for words Commented Mar 15, 2014 at 13:44

2 Answers 2

3

I think you need to change one string of your code to something like this:

$(this).val($(this).val().split(' ').slice(0, maxchars).join(' '));

This code splits text in an array of words (you may need another workflow), removes extra words and joins them back

Sign up to request clarification or add additional context in comments.

3 Comments

What about new lines ?
you can use regexps instead of ' ' string i thing something like this is what you need: /[ \n]/
If you see the demo created by RajaPrabhu, when the last word is typed and a space is put after it, the code removes the space and appends the new word to the last word. So it becomes a never ending chunk of text as the text keeps appending to the last word
0

A simple way would be to converting the full String into array of words.

For example you're having a String as:

var words = "Hi, My name is Afzaal Ahmad Zeeshan.";
var arrayOfWords = words.split(" "); // split at a white space

Now, you'll have an array of words. Loop it using

for (i = 0; i < words.length; i++) {
  /* write them all, or limit them in the for loop! */
}

This way, you can write the number of words in the document. Instead of characters!

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.