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/
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
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!
Related
I am using extendscript to build some invoices from downloaded plaintext emails (.txt)
At points in the file there are lines of text that look like "Order Number: 123456" and then the line ends. I have a script made from parts I found on this site that finds the end of "Order Number:" in order to get a starting position of a substring. I want to use where the return key was hit to go to the next line as the second index number to finish the substring. To do this, I have another piece of script from the helpful people of this site that makes an array out of the indexes of every instance of a character. I will then use whichever array object is a higher number than the first number for the substring.
It's a bit convoluted, but I'm not great with Javascript yet, and if there is an easier way, I don't know it.
What is the character I need to use to emulate a return key in a txt file in javascript for extendscript for indesign?
Thank you.
I have tried things like \n and \r\n and ^p both with and without quotes around them but none of those seem to show up in the array when I try them.
//Load Email as String
var b = new File("~/Desktop/Test/email.txt");
b.open('r');
var str = "";
while (!b.eof)
str += b.readln();
b.close();
var orderNumberLocation = str.search("Order Number: ") + 14;
var orderNumber = str.substring(orderNumberLocation, ARRAY NUMBER GOES HERE)
var loc = orderNumberLocation.lineNumber
function indexes(source, find) {
var result = [];
for (i = 0; i < source.length; ++i) {
// If you want to search case insensitive use
// if (source.substring(i, i + find.length).toLowerCase() == find) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
}
}
alert(result)
}
indexes(str, NEW PARAGRAPH CHARACTER GOES HERE)
I want all my line breaks to show up as an array of indexes in the variable "result".
Edit: My method of importing stripped all line breaks from the document. Using the code below instead works better. Now \n works.
var file = File("~/Desktop/Test/email.txt", "utf-8");
file.open("r");
var str = file.read();
file.close();
You need to use Regular Expressions. Depending on the fields do you need to search, you'l need to tweek the regular expressions, but I can give you a point. If the fields on the email are separated by new lines, something like that will work:
var str; //your string
var fields = {}
var lookFor = /(Order Number:|Adress:).*?\n/g;
str.replace(lookFor, function(match){
var order = match.split(':');
var field = order[0].replace(/\s/g, '');//remove all spaces
var value = order[1];
fields[field]= value;
})
With (Order Number:|Adress:) you are looking for the fields, you can add more fields separated the by the or character | ,inside the parenthessis. The .*?\n operators matches any character till the first break line appears. The g flag indicates that you want to look for all matches. Then you call str.replace, beacause it allows you to perfom a single task on each match. So, if the separator of the field and the value is a colon ':', then you split the match into an array of two values: ['Order number', 12345], and then, store that matches into an object. That code wil produce:
fields = {
OrderNumber: 12345,
Adresss: "my fake adress 000"
}
Please try \n and \r
Example: indexes(str, "\r");
If i've understood well, wat you need is to str.split():
function indexes(source, find) {
var order;
var result = [];
var orders = source.split('\n'); //returns an array of strings: ["order: 12345", "order:54321", ...]
for (var i = 0, l = orders.length; i < l; i++)
{
order = orders[i];
if (order.match(/find/) != null){
result.push(i)
}
}
return result;
}
I am working on my college homework. I am having a lot of difficulty with it and getting stuck. My class mates are not helping me and the instructor hasn't responded. I am hoping I might get some help/understanding here. The current assignment I am working on and it is due today is:
Create a page containing a textarea and an “analyze” button. The results area will display the frequency of words of x characters. For example, the text “one two three” contains 2 3-character words and 1 5-character word. An improvement to the original design would be to strip out any extraneous characters that may skew the count.
I am just starting it now, so I will add the code here as I update. I know I won't have a problem with the HTML part, the JavaScript will be my problem. From what I get, I will need to have a function that counts the words and the characters in each word. But it needs to exclude spaces and characters like: ,.';/. I have not run across this code before, so any input on how I should frame the javascript will be helpful. Also it seems he wants me to list how many words have the same characters? am I reading this right?
My code thus far:
<!DOCTYPE html>
<html>
<body>
<textarea id="txtarea">
</textarea>
<input type="button" id="analyze" value="Analyze" onclick="myFunction()" />
<p id="demo"></p>
<p id="wcnt"></p>
<script>
function myFunction() {
var str = document.getElementById("txtarea").value;
var res = str.split(/[\s\/\.;,\-0-9]/);
var n = str.length;
document.getElementById("demo").innerHTML = "There are " + n + " characters in the text area.";
for (var i = 0; i < res.length; i++) {
s = document.getElementById("txtarea").value;
s = s.replace(/(^\s*)|(\s*$)/gi, "");
s = s.replace(/[ ]{2,}/gi, " ");
s = s.replace(/\n /, "\n");
document.getElementById("wcnt").innerHTML = "There are " + s.split(' ').length + " words in the text area.";
}
}
</script>
</body>
</html>
Now I need to figure out how to make it count the characters of each word then output how many words have x amount of characters. Such as 5 words have 4 characters and so on. Any suggestions?
var textarea = document.getElementById("textarea"),
result = {}; // object Literal to hold "word":NumberOfOccurrences
function analyzeFrequency() {
// Match/extract words (accounting for apostrophes)
var words = textarea.value.match(/[\w']+/g); // Array of words
// Loop words Array
for(var i=0; i<words.length; i++) {
var word = words[i];
// Increment if exists OR assign value of 1
result[word] = ++result[word] || 1;
}
console.log( result );
}
analyzeFrequency(); // TODO: Do this on some button click
<textarea id="textarea">
I am working on my college-homework.
Homework I am having a lot of difficulty with it and getting stuck.
My class mates are not helping me and the instructor hasn't responded.
I am hoping I might get some help/understanding here.
</textarea>
Notice how Homework and homework (lowercase) are registered as two different words, I'll leave it to you to fix that - if necessary and implement the analyzeFrequency() trigger on some button click.
Most likely you will have to use JavaScript's split function with regex to define all the characters you do not want to include. Then loop through the resulting array and count the characters in each word.
var words = document.getElementById("words");
var analyze = document.getElementById("analyze");
analyze.addEventListener("click", function(e) {
var str = words.value;
var res = str.split(/[\s\/\.;,\-0-9]/);
for(var i = 0; i < res.length; i++) {
alert(res[i].length);
}
});
<textarea id="words">This is a test of this word counter thing.</textarea>
<br/>
<button id="analyze">
Analyze
</button>
Your instructor does NOT want you to list how may words have the same characters but rather the same number of characters. The basic algorithm:
Assign the value of the text area to a variable.
Convert that string value into an array. In javascript this could be accomplished with the String split method using a regular expression containing a character class.
Iterate over that array examining each element for its length. For each element, increment a counting object's property whose property name is the length of the element.
Iterate over the counting object's property list. Output to the result area each property name and its value.
I have a long string.
var string = "This is a long string."
I also have a function to download the string to "path".
downloadfunction{... 'echo "'+string+'" >> '+path;}
How do I execute this function for every 2 letters of the string? Read somewhere about using ".length" but not sure how to implement it in this case. I also do not want to split the string into an array. The download function should help split the string to download 2 letters progressively.
I.e. I would like to download the string 2 letters at a time.
EDIT: To clarify, the string needs to be downloaded x characters at a time as the download would break if it exceeds that limit.
Here is an example that is commented on how to do this:
var string = 'a really really really long string \
that I want to split by two letters at a time';
// this needs to be ceiling so that it always rounds up on odd numbers
// otherwise the last letter may be left out
var iterations = Math.ceil(string.length / 2);
for (var i = 0; i < iterations; i++) {
// we are iterating over half of the length but want to go two letters at a time
var j = i*2;
// make a new string with the first letter
var letters = string[j]
// this is an if statement to check if there is a second letter
// if there is concat it to the first letter
// otherwise the last set of an odd length would concat `undefined` to it
if (string[j+1]) { letters += string[j+1]; }
// call your function here passing `letters` to it
downloadfunction{... 'echo "' + letters + '" >> '+path;}
}
count string length
divide by 2 round up or down what ever you like
then do a for loop of the amount after the devision.
Somethig like this
//Your string that is downloaded
var string = "This is a long string."
//calculate the amount of character in the string
var amount = string.length;
//divide the string by 2
var roundnr = amount/2;
for (var i=0;i<Math.round(roundnr);i++)
{
//do something here for every 2 characters in the string
}
I have a .txt file with this structure:
chair 102
file 38
green 304
... ...
It has 140.000 elements.
Before introducing the numbers I used javascript and jQuery:
$(function () {
$.get('/words.txt', function (data) {
words = data.split('\n');
});
But because I have now numbers how could I treat separately the strings and the numbers?
Since this helped, I'll post as an answer:
Your format is <word><space><num>\n
You split on new line, so now you have an array of <word><space><num> which you should be able to split on space.
Then you can get the word part as myarray[0] and the number part as myarray[1].
you could split at each new line and then split each element at space, but this will gives you array of array of words .
you could replace line with space and then split at space
ie:
words = data.replace(/\n/g,' ').split(' ');
An efficient way of handling this problem is to replace all the line breaks with spaces, then split the resulting string by the spaces. Then use what you know about the position of the elements to determine whether you're dealing with a number or a string:
var resultArr = data.replace(/\n/g, " ").split(" ")
for(var i = 0; i < resultArr.length; i++) {
if(i % 2) {
// even indexes represent the word
console.info("word = " + resultArr[i]);
} else {
// odd indexes represent the number
console.info("number = " + resultArr[i]);
}
}
Depending on whether or not there's a line break at the end of the set, you may need to handle that case by looking for an empty string.
I have been given a task...
"count the number of words in the string "tx_val" that have 3,4,5 or 6 characters
show these four counts on a single line separated by commas"
I have been trying multiple different loop statements but I cannot seem to get the right answer.
Here is the code I was given to work with :
<html>
<head>
<script language="javascript">
<!--
function fred()
{
var tx_val=document.alice.tx.value;
len_tx=tx_val.length
-->
</script>
</head>
<body>
<form name="alice">
<b>Assignment #1 Javascript</b>
<p>
The text box below is named "tx". The form is named "alice".
<p>
<input type="text" name="tx" formname="alice" size="50" value="the quick brown fox jumped over the lazy dogs back">
</form>
The regular expression /\b\w{3,6}\b/ matches a "word" of 3 through 6 characters in length. Now that definition of "word" may or may not suit your purposes, but it's probably close.
With that, you could do something like:
var matches = theString.match(/\b\w{3,6}\b/g).length;
to get the count.
The escape "\w" matches any "word" character, which to JavaScript means alphanumerics and underscore. If you don't like that, you could construct your own character class. For example, if you only care about words made up of letters, you could do:
var matches = theString.match(/\b[a-zA-Z]{3,6}\b/g).length;
The "\b" escape is a zero-length match for a word delineation. It matches either the start or the end of a word, without itself "consuming" any characters while doing so.
edit — sorry I had originally mistyped a "." in the {3,6} qualifier (and I almost did it again just now :-) — should have been commas.
You can first split the words into an array using the split method. Then you can loop over that array using its forEach method and counting the length of each word.
Here are some simple questions that might help you build up a straightforward approach:
What's a 'word'? How can you find all of them?
Can you put those words into an array of strings?
Can you loop through an array?
Can you increment a counter when looping?
Can you tell me how many letters are in a specific word?
Can you conditionally increment a counter based on an if statement?
Can you nest two loops?
That said, here's how I personally would do it (which probably would not satisfy your homework requirements if you copy/pasted it without understanding it):
var text = "Oh HAI, is this the longest text allowd?"
for (var counts=[],l=3;l<=6;++l){
var re = new RegExp('\\b\\w{'+l+'}\\b','g');
var words = text.match(re);
counts.push(words ? words.length : 0);
}
console.log(counts.join(','));
//-> 2,2,0,1
I don't know Javascript. But your code should go like this:
function fred()
{
var threeCharacterLong = 0;
var fourCharacterLong = 0;
var fiveCharacterLong = 0;
var sixCharacterLong = 0
var tx_val=document.alice.tx.value;
var splittedArray = tx_val.Split(" ");
foreach (var word in splittedArray)
{
if (word.length == 3)
threeCharacterLong++;
else if (word.length == 4)
fourCharacterLong ++;
else if (word.length == 5)
fiveCharacterLong ++;
else if (word.length == 6)
sixCharacterLong ++;
}
}