i am trying to put a limit on number of characters in a word. i am successful to find, if someone is entering more then 15 character.i am displaying a message right now. what i want to do is, if some one enter more then 15 characters ... the java script display a alert and then delete all letters leaving first 14 characters in that word. i tried to find some helpful functions but never found something useful.
i want to check for the character limit dynamically when the user is still entering.
my code is half complete but it has one flaw. it is displaying the message when a count is reaching more then 15 it displays a alert. now user can still save that string that has more than 15 char in a word. hope i explained it all.thanks to all,for everyone that is gonna put some effort in advance.
<textarea id="txt" name="area" onclick="checkcharactercount()"></textarea>
function checkcharactercount(){
document.body.addEventListener('keyup', function(e) {
var val = document.getElementById("txt").value;
var string = val.split(" ");
for(i=0;i<string.length; i++) {
len = string[i].length;
if (len >= 15) {
alert('you have exceeded the maximum number of charaters in a word!!!');
break;
}
}
});
}
Does this work like you want it to?
var textArea = document.getElementById('txt');
textArea.addEventListener('keyup', function () {
var val = textArea.value;
var words = val.split(' ');
for (var i = 0; i < words.length; i++) {
if (words[i].length > 14) {
// the word is longer than 14 characters, use only the first 14
words[i] = words[i].slice(0, 14);
}
}
// join the words together again and put them into the text area
textArea.value = words.join(' ');
});
<textarea id="txt" name="area"></textarea>
Related
I'm making a Ukrainian phonetic keyboard. People type in English, and the letters automatically change to the corresponding Ukrainian characters. However, when I'm using it, I sometimes need to write myself notes in English (they serve the same purpose as comments in code- for other people and for myself).
I'd like to indicate the start of a comment with a tag ("<"). How can I check if there's currently an open tag?
I'm thinking something like this:
if (number of "<" is greater than ">") {//if a tag has been opened and not closed
//disable translation, type in English
}
I understand how to disable the translation- however, I'm unsure about the
"if"
How can I check if
number of "<" is greater than ">"
Thanks!
You can count number of specific characters using .match()
In your case
var string = "<<<>>";
if ((string.match(/</g)||[]).length > (string.match(/>/g)||[]).length) {
console.log("More");
}
else {
console.log("Less or equal");
}
counting each of them is like below
var countGreaterThan = (temp1.match(/</g) || []).length;
var countLessThan = (temp1.match(/</g) || []).length;
and temp is the string value of the textarea
Depending on where your data is, you can do:
var data = document.querySelector('#data-container').innerHTML;
var isOpenTagPresent = getSymbolCount('<') > getSymbolCount('<');
if(isOpenTagPresent) {
//execute your logic
}
function getSymbolCount(symbol) {
var count = 0;
for(var i = 0; i < data.length; ++i) {
if(data[i] === symbol) {
count++;
}
}
return count;
}
Hope this helps, cheers!
Here is my code:
$("body").on('input', 'textarea', function() {
var el = $(this);
var len = el.val().length;
if (len <= 1){
var x = new RegExp("[A-Za-z]"); // is ascii
var isAscii = x.test(el.val().substring(0, 1));
if(isAscii){
el.css("direction", "ltr");
} else {
el.css("direction", "rtl");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>dynamic direction</textarea>
My current code changes the direction of such a textarea. It is based on the first character:
If the first character is either a Persian character or a sign, it sets rlt direction to that textarea.
If the first character is a English character, it sets lrt direction to that textarea.
Well that's not what I want. I want this:
If the first letter (not signs) is a English letter, then set the textarea ltr direction. Otherwise set it rtl.
Here is some examples:
var test = "..!"; // rtl
var test = "te"; // ltr
var test = "!te"; // ltr
var test = "..ق"; // rtl
var test = "مب"; // rtl
var test = "eس"; // ltr
var test = "سe"; // rtl
var test = "^سe"; // rtl
var test = ".32eس"; // ltr
How can I do that?
If I read the question correctly, the goal is to have the text read left-to-right if the first non-symbol/sign/punctuation character is an ASCII character, otherwise read right-to-left.
I think all you need to do is change your regex to first match 0 or more symbols/signs/punctuation-marks, and then to test if the next character is an ASCII character.
The regex [-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/] is a fairly complete regex for symbols/signs/punctuation-marks, found here: https://stackoverflow.com/a/8359631/4132627. You may need to add to it as you see fit.
Putting that together we'd get something like [-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]*[A-Za-z]. The * between the two character groups means "match 0 or more of the previous group".
I've updated your snippet with that regex and it appears to work as expected. Also removed the length check as this needs to run no matter how many characters there are.
This probably isn't perfect - there are many cases probably being left out. You may need to play with it a bit. For example, should that second character group also include numbers ([A-Za-z0-9])?
In any case, I hope this helps!
$("body").on('input', 'textarea', function() {
var el = $(this);
var len = el.val().length;
//if (len <= 1){
var x = /^[-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/]*[A-Za-z]/; // is ascii
var isAscii = x.test(el.val());
if(isAscii){
el.css("direction", "ltr");
} else {
el.css("direction", "rtl");
}
//}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>dynamic direction</textarea>
You can have an array of persian, or any right to left, letters and check whether the first letter exists in the array using .inArray() function, something like this:
jsFiddle
var persianLetters = ['آ ', 'ا', 'ب', 'پ', 'ت', 'ث','ج', 'چ', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز' , 'ژ', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق', 'ک', 'گ' ,'ل', 'م', 'ن', 'و', 'ه', 'ى'];
$("#ta").on('input', function() {
var el = $(this);
var txt = el.val();
var len = txt.trim().length;
if (len <= 1){
var x = txt.substring(0, 1);
// if the letter is not in the array, the $.inArray() will return -1
console.log($.inArray(x, persianLetters));
if($.inArray(x, persianLetters) > -1){
el.css("direction", "rtl");
} else {
el.css("direction", "ltr");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea name="txt" id="ta" cols="30" rows="10"></textarea>
I'm sort of creating typing tutor with custom options.
Not a professional (don't get mad at me for being wrong-person-wrong place) but thanks to helpful forums like stackoverflow.com and contributing traffic/people I'm able to pull it out in a day or two.
Directly now, here!
while (i < len+1){
if(boxarray[i] == orgarray[i]){
++i;
actualScore = i - 1;
}
I've searched already, '==' operator is of no use, I will not go for JSON.encode. I met similar solution at this page . But in my case I've to loop through each word while comparing two sentences. Detail is trivial, if someone please help me solve above, I won't return with complain on the same project, promise.
Okay I'm putting more code if it can help you help me.
var paratext = document.getElementById('typethis').innerHTML;
var orgstr = "start typing, in : BtXr the yellow box but. please don't shit." ;
var boxtext = document.getElementById('usit').value;
var endtrim = boxtext;
var actualScore;
var orgarray = listToArray(orgstr," ");
var boxarray = listToArray(boxtext," ");
var len = boxarray.length;
var i = 0;
var actualScore; //note var undefined that's one mistake I was making [edit]
if(orgstr.indexOf(boxtext) !== -1){
while (i < len+1){
if(boxarray[i] == orgarray[i]){
++i;
actualScore = i - 1;
}
}
alert(actualScore);
}
If I follow what you're after how about something like this:
http://jsfiddle.net/w6R9U/
var s1 = 'The dog sleeps';
var s2 = 'the dog jogs';
var s1Parts= s1.split(' ');
var s2Parts= s2.split(' ');
var score = 0;
for(var i = 0; i<s1Parts.length; i++)
{
if(s1Parts[i] === s2Parts[i])
score++;
}
"The dog sleeps" and "the dog sleeps" results in a score of 2 because of case (which could be ignored, if needed). The example above results in a score of 1. Could get a percent by using the length of the sentences. Hope this helps! If nothing else might get you started.
The following will compare each individual character, decreasing the "actualScore" for each inequality:
http://jsfiddle.net/ckKDR/
var sentence1 = "This is the original sentence.", // original text
sentence2 = "This is teh originel sentence.", // what the user typed
length = sentence1.length,
actualScore = length, // start with full points
i = 0;
while(i<length){
if(sentence1[i]!==sentence2[i]){
actualScore--; // subtract 1 from actual score
}
i++; // move to the next index
}
alert("'sentence2' is "+Math.round(100*(actualScore/length))+"% accurate");
Let's say the input is your two sentences as strings.
Then the first thing to do is to create two temporary strings, with all the non-word characters eliminated (e.g. punctuation characters). Split the sentences into string arrays by word delimiters.
Then you can assign an integer variable to score. Create an outer loop and an inner loop for the two sentences. When the words match in the sentences, increment the variable by 1, remove the word from the 2nd sentence (replace the word with a non-word character) and break out of the inner loop.
Also, use this operator for word comparison instead:
===
Your problem is
if (boxarray[i] = orgarray[i])
The single = is the assignment operator. Replace it with
===
to be a comparison.
You are not comparing you are assigning
if(boxarray[i] = orgarray[i]){
^^^
So it will be true on each iteration. Fix the typo to actually perform the check you want
if(boxarray[i] === orgarray[i]){
^^^
And how you are calculating the score looks to be wrong. You should be doing something like
var score = orgstr.length;
while...
if(boxarray[i] === orgarray[i]){
score--;
}
{
string1="string1";
string2="string2 is here";
changepercent(string1,string2);
}
function changepercent(string1,string2) {
var s1Parts= string1.split(' ');
var s2Parts= string2.split(' ');
var matched = 0;
for(var i = 0; i<s1Parts.length; i++)
{
for(var j = 0; j<s2Parts.length; j++)
{
if(s1Parts[i] === s2Parts[j])
matched++;
}
}
var percentage=(matched/Math.max(s1Parts.length, s2Parts.length))*100;
console.log(matched);
console.log(percentage);
if(percentage<50)
{
console.log("Change Above 50%");
}
}
Slightly modified first code
Current
I’ve re-worked this syllable counter script to:
Get the value of textarea 1.
Count the number of syllables in textarea 1.
Display the results in textarea 2.
Update the count every time the value of textarea 1 is edited.
Act as a function (be able to run in multiple instances if wanted).
Example function of current code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
11
Current code
Here is the existing code as a JSFiddle.
Goal
I would like this script to:
Count the syllables of textarea 1 on a per line basis: presumably by splitting the textarea 1 value where there are line breaks e.g. .split('\n');.
Output the results, showing the total number of syllables counted per line.
Example function of desired code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
6
3
2
Problem
I’m quite stuck as to how to do this and would really appreciate any help or JSFiddle showing how to work with the existing code to achieve this.
Notes
For anyone who may be interested using in the syllable count function code itself: it’s not 100% accurate and fails on some words but gives a good general idea.
Try this and let me know if it's what you needed.
Callouts:
I created an array that spits the lines up stores them var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);.
Then loop through that array and do exactly what you did before, but on each array entry. Then store the results in tempArr, and display the tempArr results.
See Fiddle
function $count_how_many_syllables($input) {
$("[name=set_" + $input + "]").keyup(function () {
var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);
var tempArr = [];
var $content;
var word;
var $syllable_count;
var $result;
for(var i = 0; i < arrayOfLines.length; i++){
$content = arrayOfLines[i];
word = $content;
word = word.toLowerCase();
if (word.length <= 3) {
word = 1;
}
if (word.length === 0) {
return 0;
}
word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '')
.replace(/^y/, '')
.match(/[aeiouy]{1,2}/g).length;
$syllable_count = word;
$result = $syllable_count;
tempArr.push($result);
}
$("[name=set_" + $input + "_syllable_count]").val(tempArr);
});
}
(function($) {
$count_how_many_syllables("a");
})(jQuery);
I have a text area that I need to parse. Each new line needs to be pulled out and an operation needs to be performed on it. After the operation is done the operation needs to be run on the next line. This is what I have at the moment. I know the indexOf search won't work because it's searching character by character.
function convertLines()
{
trueinput = document.getElementById(8).value; //get users input
length = trueinput.length; //getting the length of the user input
newinput=trueinput; //I know this looks silly but I'm using all of this later
userinput=newinput;
multiplelines=false; //this is a check to see if I should use the if statement later
for (var i = 0; i < length; i++) //loop threw each char in user input
{
teste=newinput.charAt(i); //gets the char at position i
if (teste.indexOf("<br />") != -1) //checks if the char is the same
{
//line break is found parse it out and run operation on it
userinput = newinput.substring(0,i+1);
submitinput(userinput);
newinput=newinput.substring(i+1);
multiplelines=true;
}
}
if (multiplelines==false)
submitinput(userinput);
}
So for the most part it is taking the userinput. If it has multiply lines it will run threw each line and seperatly and run submitinput. If you guys can help me I'd be eternally thankful. If you have any questions please ask
Line breaks within the value of a textarea are represented by line break characters (\r\n in most browsers, \n in IE and Opera) rather than an HTML <br> element, so you can get the individual lines by normalizing the line breaks to \n and then calling the split() method on the textarea's value. Here is a utility function that calls a function for every line of a textarea value:
function actOnEachLine(textarea, func) {
var lines = textarea.value.replace(/\r\n/g, "\n").split("\n");
var newLines, i;
// Use the map() method of Array where available
if (typeof lines.map != "undefined") {
newLines = lines.map(func);
} else {
newLines = [];
i = lines.length;
while (i--) {
newLines[i] = func(lines[i]);
}
}
textarea.value = newLines.join("\r\n");
}
var textarea = document.getElementById("your_textarea");
actOnEachLine(textarea, function(line) {
return "[START]" + line + "[END]";
});
If user is using enter key to go to next line in your text-area you can write,
var textAreaString = textarea.value;
textAreaString = textAreaString.replace(/\n\r/g,"<br />");
textAreaString = textAreaString.replace(/\n/g,"<br />");
textarea.value = textAreaString;
to simplify the answers, here is another approach..
var texta = document.getElementById('w3review');
function conv (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;
}
<textarea id="targetted_textarea" rows="6" cols="50">
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="conv('targetted_textarea','destination')" id="convert">Convert</button>
<div id="destination">Had not been fetched yet click convert to fetch ..!</div>