I am trying to implement a word counter in textbox. I am using the links below:
JS Fiddle
Second link
<textarea name="myMessage" onkeyup="wordcount(this.value)"></textarea>
<script type=""text/javascript"">
var cnt;
function wordcount(count) {
var words = count.split(/\s/);
cnt = words.length;
var ele = document.getElementById('w_count');
ele.value = cnt;
}
document.write("<input type=text id=w_count size=4 readonly>");
</script>
Word counter is working fine. But my scenario is like as below:
for word "Most Suitable Match" if user type short form as "MSM" then MSM also shall be counted as 3 words.
In the same way if there is name of college like "DAV" then it shall also be counted as 3 words.
Please suggest !!
I have make a simple function:
var regex = [/DAV/g, /MAC/g];
function countWords() {
var count = [];
regex.forEach(function(reg) {
var m = text.match(reg);
if (m) {
count = count.concat(m);
}
});
// the number of known acronym wrote in the text
var acronyms = count.length;
// how much words generated from an acronym (e.g. DAV === 3 words; AB === 2 words and so on)
var wordsFromAcronyms = count.join().replace(/,/g,'').length;
// how many words wrote (this is equal to your code)
var rawWords = text.match(/\S+/g).length;
// compute the real number
return rawWords - acronyms + wordsFromAcronyms;
}
It counts the number of the wrote acronym (the list of the known acronyms is stored in regex array), then count how much words are generated by the acronyms (wordsFromAcronym), and then substract the number of acronyms (acronyms) from the total words (rawWords) and then add the wordsFromAcronym.
Here is a PLNKR.
Try this. I am on my mobile so I cannot make an example easily
This will count all words in all uppercase as acronyms
<textarea name="myMessage" onkeyup="wordcount(this.value)"></textarea>
<input type=text id=w_count size=4 readonly>
<script type=""text/javascript"">
function wordcount(message) {
var words = message.split(/\s/);
var cnt = words.length;
for (var i=0;i<cnt;i++) {
if (words[i].length>1 && words[i].match(/^[A-Z]*$/)) cnt += words[i].length-1)
}
var ele = document.getElementById('w_count');
ele.value = cnt;
}
</script>
Using a javascript function to prevent exceeding the length of a textfield, but to still allow pasting & editing within it. Needs to work in IE8 & Firefox.
$(function() {
var helper = document.createElement('textarea');
//if (!('maxLength' in helper)) {
var supportsInput = 'oninput' in helper,
ev = supportsInput ? 'input' : 'propertychange paste keyup',
handler = function() {
var maxlength = +$(this).attr('maxlength');
if (this.value.length > maxlength) {
this.value = this.value.substring(0, maxlength);
}
};
$('textarea[maxlength]').on(ev, supportsInput ? handler : function() {
var that = this;
setTimeout(function() {
handler.call(that);
}, 0);
});
//}
});
It works okay if the text is on one line (testing with maxLength = 25). However, it doesn't do carriage returns & line feeds or account for them properly.
For example, if I enter the following text on one line:
1111122222333334444455555
it uses all 25 characters.
However, if I enter text on each line & hit enter, this is what I am able to enter:
11111
22222
33333
4444
Which is only 22 characters. I know that it is detecting a carriage return, because when I put in:
11111
a character counter shows 5. When I hit the enter key, the counter goes to 6, if I enter 22222 the counter is now 11.
The code I'm using to count the characters is:
$("#myTextArea").keyup(function() {
var j = $(this).val().length;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
I thought the issue might be some code I put in to resize the TextArea automatically, but it isn't. I'm sure I am just missing something on the code & would appreciate input on what I'm doing wrong & haven't seem to have figured out yet.
I stumbled upon the answer myself. It turns out the character counter I was using was not accurately counting the line breaks in the <textarea>.
Although I was using IE8, I found the answer in a question about Chrome counting characters wrong in textarea with maxLength attribute. That question is here.
The code I used before:
$("#myTextArea").keyup(function() {
var j = $(this).val().length;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
has been modified to:
$("#myTextArea").keyup(function() {
var x = $("#myTextArea").val();
var newLines = x.match(/(\r\n|\n|\r)/g);
var addition = 0;
if (newLines != null) {
addition = newLines.length;
}
var j = x.length + addition;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
The embedded new lines must be transmitted as a CR LF pair - actually 2 characters. Thanks to the posters in the other thread for their help.
I have a text area where each line contains Integer value like follows
1234
4321
123445
I want to check if the user has really enetered valid values and not some funny values like follows
1234,
987l;
For that I need to read line by line of text area and validate that.
How can i read line by line of a text area using javascript?
Try this.
var lines = $('textarea').val().split('\n');
for(var i = 0;i < lines.length;i++){
//code here using lines[i] which will give you each line
}
This works without needing jQuery:
var textArea = document.getElementById("my-text-area");
var arrayOfLines = textArea.value.split("\n"); // arrayOfLines is array where every element is string of one line
Two options: no JQuery required, or JQuery version
No JQuery (or anything else required)
var textArea = document.getElementById('myTextAreaId');
var lines = textArea.value.split('\n'); // lines is an array of strings
// Loop through all lines
for (var j = 0; j < lines.length; j++) {
console.log('Line ' + j + ' is ' + lines[j])
}
JQuery version
var lines = $('#myTextAreaId').val().split('\n'); // lines is an array of strings
// Loop through all lines
for (var j = 0; j < lines.length; j++) {
console.log('Line ' + j + ' is ' + lines[j])
}
Side note, if you prefer forEach a sample loop is
lines.forEach(function(line) {
console.log('Line is ' + line)
})
This would give you all valid numeric values in lines. You can change the loop to validate, strip out invalid characters, etc - whichever you want.
var lines = [];
$('#my_textarea_selector').val().split("\n").each(function ()
{
if (parseInt($(this) != 'NaN')
lines[] = parseInt($(this));
}
A simple regex should be efficent to check your textarea:
/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"
A simplifyied Function could be like this:
function fetch (el_id, dest_id){
var dest = document.getElementById(dest_id),
texta = document.getElementById(el_id),
val = texta.value.replace(/\n\r/g,"<br />").replace(/\n/g,"<br />");
dest.innerHTML = val;
}
for the html code below (as an example only):
<textarea id="targetted_textarea" rows="6" cols="60">
At https://www.a2z-eco-sys.com you will get more than what you need for your website, with less cost:
1) Advanced CMS (built on top of Wagtail-cms).
2) Multi-site management made easy.
3) Collectionized Media and file assets.
4) ...etc, to know more, visit: https://www.a2z-eco-sys.com
</textarea>
<button onclick="fetch('targetted_textarea','destination')" id="convert">Convert</button>
<div id="destination">Had not been fetched yet click convert to fetch ..!</div>
I want to display YouTube videos on my website, but I need to be able to add a unique id for each video that's going to be shared by users. So I put this together, and I have run into a little problem. I am trying to get the JavaScript to add a random string for the div id, but it's not working, showing the string:
<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (! length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
var div = randomString(8);
</script>
<div id='div()'>This text will be replaced</div>
<script type='text/javascript'>
jwplayer('div()').setup({
'flashplayer': 'player.swf',
'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
'controlbar': 'bottom',
'width': '470',
'height': '320'
});
</script>
I really like this function:
function guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
From Create GUID / UUID in JavaScript?
2018 edit: I think this answer has some interesting info, but for any practical applications you should use Joe's answer instead.
A simple way to create a unique ID in JavaScript is to use the Date object:
var uniqid = Date.now();
That gives you the total milliseconds elapsed since January 1st 1970, which is a unique value every time you call that.
The problem with that value now is that you cannot use it as an element's ID, since in HTML, IDs need to start with an alphabetical character. There is also the problem that two users doing an action at the exact same time might result in the same ID. We could lessen the probability of that, and fix our alphabetical character problem, by appending a random letter before the numerical part of the ID.
var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
var uniqid = randLetter + Date.now();
This still has a chance, however slim, of colliding though. Your best bet for a unique id is to keep a running count, increment it every time, and do all that in a single place, ie, on the server.
Here is the reusable function to generate the random IDs :
function revisedRandId() {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
}
// It will not start with the any number digit so it will be supported by CSS3
I think some folks here haven't really focused on your particular question. It looks like the problem you have is in putting the random number in the page and hooking the player up to it. There are a number of ways to do that. The simplest is with a small change to your existing code like this to document.write() the result into the page. I wouldn't normally recommend document.write(), but since your code is already inline and what you were trying do already was to put the div inline, this is the simplest way to do that. At the point where you have the random number, you just use this to put it and the div into the page:
var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');
and then, you refer to that in the jwplayer set up code like this:
jwplayer(randomId).setup({
And the whole block of code would look like this:
<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
if (! length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({
'flashplayer': 'player.swf',
'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
'controlbar': 'bottom',
'width': '470',
'height': '320'
});
</script>
Another way to do it
I might add here at the end that generating a truly random number just to create a unique div ID is way overkill. You don't need a random number. You just need an ID that won't otherwise exist in the page. Frameworks like YUI have such a function and all they do is have a global variable that gets incremented each time the function is called and then combine that with a unique base string. It can look something like this:
var generateID = (function() {
var globalIdCounter = 0;
return function(baseStr) {
return(baseStr + globalIdCounter++);
}
})();
And, then in practical use, you would do something like this:
var randomId = generateID("myMovieContainer"); // "myMovieContainer1"
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({
i like this simple one:
function randstr(prefix)
{
return Math.random().toString(36).replace('0.',prefix || '');
}
since id should (though not must) start with a letter, i'd use it like this:
let div_id = randstr('youtube_div_');
some example values:
youtube_div_4vvbgs01076
youtube_div_1rofi36hslx
youtube_div_i62wtpptnpo
youtube_div_rl4fc05xahs
youtube_div_jb9bu85go7
youtube_div_etmk8u7a3r9
youtube_div_7jrzty7x4ft
youtube_div_f41t3hxrxy
youtube_div_8822fmp5sc8
youtube_div_bv3a3flv425
I also needed a random id, I went with using base64 encoding:
btoa(Math.random()).substring(0,12)
Pick however many characters you want, the result is usually at least 24 characters.
Based on HTML 4, the id should start from letter:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
So, one of the solutions could be (alphanumeric):
var length = 9;
var prefix = 'my-awesome-prefix-'; // To be 100% sure id starts with letter
// Convert it to base 36 (numbers + letters), and grab the first 9 characters
// after the decimal.
var id = prefix + Math.random().toString(36).substr(2, length);
Another solution - generate string with letters only:
var length = 9;
var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);
Or you could use Cripto since it's already built in(except in IE11, I swear these guys havent updated in years!)
https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#Examples
var id = new Uint32Array(10);
window.crypto.getRandomValues(id);
I also found this:
https://gist.github.com/6174/6062387#gistcomment-3255605
let length = 32;
let id = crypto.randomBytes(length).toString("base64");
There's a lot of ways to do this, but for most people, there's no reason to reinvent the wheel :)
A edited version of #jfriend000 version:
/**
* Generates a random string
*
* #param int length_
* #return string
*/
function randomString(length_) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
if (typeof length_ !== "number") {
length_ = Math.floor(Math.random() * chars.length_);
}
var str = '';
for (var i = 0; i < length_; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
For generating random ids, you can also use the standard crypto API with its randomUUID() function which is available in node.js (>=v16.7.0) and all relevant browsers except Safari:
const uuid = crypto.randomUUID()
console.log(uuid)
// prints e.g. "7f3f4512-fcf9-45fe-b726-512bba403426"
I would suggest that you start with some sort of placeholder, you may have this already, but its somewhere to append the div.
<div id="placeholder"></div>
Now, the idea is to dynamically create a new div, with your random id:
var rndId = randomString(8);
var div = document.createElement('div');
div.id = rndId
div.innerHTML = "Whatever you want the content of your div to be";
this can be apended to your placeholder as follows:
document.getElementById('placeholder').appendChild(div);
You can then use that in your jwplayer code:
jwplayer(rndId).setup(...);
Live example: http://jsfiddle.net/pNYZp/
Sidenote: Im pretty sure id's must start with an alpha character (ie, no numbers) - you might want to change your implementation of randomstring to enforce this rule. (ref)
May I an share an intuitive way to generate a randomID ?
const getRandomID = (length: number) => {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
Here is an easy one liner:
const generateUniqueID = (idLength) => [...Array(idLength).keys()].map((elem)=>Math.random().toString(36).substr(2, 1)).join("")
Where all you do is enter the idLength and it will return a unique id of that length.
generateUniqueID(23)
>>>'s3y9uebzuo73ih79g0s9p2q' // Id of length 23
First. Assign an id to your div. Like this:
<div id="uniqueid">This text will be replaced</div>
After that, add inside your <script> tag following code:
Document.getElementById("uniqueid").id = randomString(8);
window.btoa(String.fromCharCode(...window.crypto.getRandomValues(new Uint8Array(5))))
Using characters except ASCII letters, digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML5, an ID should start with a letter for compatibility.
function id(prefix = '', length = 7) {
let result = prefix;
for(let i = 0; i < length; i++) {
const random = Math.random();
result += String.fromCharCode(Math.floor(random * 26) + (random < .5 ? 65 : 97));
}
return result;
}
a random number between 0 and 25 is generated then added to either 65 or 97. When added to 65 it will give you an ascii code for a capital letter and when added to 97, an ascii code for a small letter.
Just use built-int crypto.randomUUID() which is supportted by all major browsers:
let uuid = crypto.randomUUID();
console.log(uuid);
This should be a quickie, but I'm scratching my head as to why this bit of JavaScript isn't working for me. The goal is to take the value of an input box (string of words separated by spaces), list these words as items in an array, and remove those which are fewer than 3 characters:
var typed = $('input').val();
var query = typed.split(" ");
var i=0;
for (i=0; i<query.length; i++) {
if (query[i].length < 3) {
query.splice(i,1);
}
}
Have this running onkeyup for the input box and it seems to work, but only about 50% of the time (strings of 1 and 2 characters somehow find their way into the array on occasion). Any suggestions would be hugely appreciated.
The problem is that you are iterating while removing the elements. Consider this array:
["he", "l", "lo world"]
Initially your loop starts at index 0 and removes "he" from the array. Now the new array is
["l", "lo world"]
In the next iteration i will be 1, and you will check "lo world"'s length, thus ignoring the "l" string altogether.
Use the filter method in Array to remove the unwanted elements.
var biggerWords = query.filter(function(word) {
return word.length >= 3;
});
Besides the iterating problem, you may also see unexpected entries if you type multiple spaces
try
var query = typed.split(/\s+/);
This way it will split on any number of spaces, instead of each individual one
The problem is that you're slicing the array while counting forward. Think about it...if you take an index point out of the array, thereby shortening it by one, incrementing i and moving on to the next one actually moves one further than you want, completely missing the next index. Increment i--, start at query.length-1, and make the condition that i>=0. For an example of this in action, check it out here:
http://jsfiddle.net/kcwjs/
CSS:
input {
width:300px;
}
HTML:
<input id="textbox" type="text" />
<div id="message"></div>
Javascript:
$(document).ready(function() {
$('#textbox').keyup(checkStrings);
});
function checkStrings(e) {
var typed = $('#textbox').val();
if (typed == "") return false;
var query = typed.split(" ");
var querylen = query.length;
var acceptedWords = '';
var badWords = '';
for (var i = querylen-1; i >= 0; i--) {
if (query[i].length < 3) {
badWords += query[i] + " ";
} else {
acceptedWords += query.splice(i,1) + " ";
}
}
$('#message').html("<div>Bad words are: " + badWords + "</div>" +
"<div>Good words are: " + acceptedWords + "</div>");
}
Try this code, it get's rid of any 3 character words, as well as making sure no empty array elements are created.
typed.replace(/(\b)\w{1,3}\b/g,"$1");
var query = typed.split(/\s+/);
hey i think you should use a new array for the result. since you are removing the element in array. the length is changed. here is my solution
var typed = "dacda cdac cd k foorar";
var query = typed.split(" ");
var i=0;
var result = [];
for (i=0; i<query.length; i++) {
if (query[i].length >= 3) {
result.push(query[i]);
}
}