Repeat a function in Javascript with .length - javascript

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
}

Related

Read numbers from <pre>

I am trying to calculate certain numbers in an array of numbers in a pre tag. Such as count how many of the numbers are 7 or higher.
For example, I have this
<pre class="data">2 7 3 1 2
6 6 2 5 3
8 2 5 9 9
5 10 5 6 10
2 10 3 </pre>
I've figured out how to get to the numbers in a general way:
document.getElementsByTagName ('PRE')[0].firstChild.data = document.getElementsByTagName ('PRE')[0].firstChild.data.replace (/\t+$/, '')
But I do not know how to get at the individual numbers. Is it an array? Or a list of numbers that I need to parse by space?
I've looked at this thread: Using <pre> tag to display data in columns? and tried to use a for loop grabbing $entry[i], but I am not able to read individual numbers.
The following will give you a 2-dimensional array:
var str = document.getElementsByTagName('pre')[0].textContent;
str // take the string and
.split('\n') // break it into an array of lines;
.map(function(line) { // then transform each line by
return line // taking the line,
.trim() // removing leading and trailing spaces,
.split(/\s+/) // and breaking it into an array at whitespace,
.map(Number); // with each piece cast to a number.
});
http://jsfiddle.net/Lwkw4ee4/
String.prototype.trim = function() { // just in case of an old browser
return this.replace(/^\s+|\s+$/gm,'');
}
var str = document.getElementById('data').innerHTML.trim();
var data = str.split(/\s+/);
alert(data);
data will be an 1D array of numbers (to be accurate - strings with numbers, but it does not matter - it is easy to cast).
http://jsbin.com/mepulu/2/edit
var text = document.getElementsByClassName('data')[0].innerHTML; // Text
var values = text.split(/\s+/); // Array of strings
var numbers = values.map(function(num) {
return parseInt(num, 10);
});
numbers; // Array of integers
The content of the pre tag is just text. In order to access the numbers, you have to parse the text. I'm assuming you just need the list of numbers, and there is no significance to the columns.
If this is true, what you need to do is split the text on whitespace, and then process each item:
var number_string = document.getElementsByTagName ('PRE')[0].firstChild.data;
var numbers = number_string.split(/[\s]+/);
var a_number;
for (var i = 0; i <= numbers.length; i++) {
a_number = parseInt(numbers[i]); // assuming the numbers are whole numbers.
}
Note that numbers[i] is actually a string representation of the number, so you need to use parseInt(numbers[i]) to get the real number. (or parseFloat(numbers[i]) if they are not whole numbers)
Hope that's helpful.
Jay

Using String.substring for Words

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!

Extract strings in a .txt file with javascript

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.

JS: determine amount of occurrences in a string

Is there a way to determine the number of times a letter occurs inside another string?
if not, can you determine the number of times a string is in an array
if you can do it with the array, how can you split 2 words, such as: Hello, World! into an array of 2 words, like this:
["Hello", "World"]
Sure. A simple one liner that comes to mind is
var numOccurrences = str.split("<char>").length -1
where can be replaced with whatever character (or string) you want to test for
That will split the string on each occurrence and then take the length of the resulting array -1. Which will tell you the number of occurrences.
If you want to do it while ignoring upper/lower case, you can use regex
str.match(/<char>/gi).length
The number of times a letter occurs in a string
This can be found as follows:
"Hello World Hello World!".match(/e/g).length // Will result in 2
/e/g is a regular expression that matches the letter 'e'. The 'g' stands for "global" and gets all the occurances in a string.
String in an array
This can be found as follows:
var arrayOfStrings = ["Hello", "World", "Hello", "World"],
wordCount = 0,
i;
for (i = 0; i < arrayOfStrings.length; i += 1) { // Remember to optimise length call
if (arrayOfStrings[i] === "Hello") {
wordCount += 1;
}
}
console.log(wordCount) // This will log 2

RegEx for filling up string

I have the following input:
123456_r.xyz
12345_32423_131.xyz
1235.xyz
237213_21_mmm.xyz
And now I need to fill up the first connected numbers to 8 numbers leading with 0:
00123456_r.xyz
00012345_32423_131.xyz
00001235.xyz
00237213_21_mmm.xyz
My try was to split a the dot, then split (if existing) at the underscore and get the first numbers and fill them up.
But I think there will be a more efficient way with the regex replace function with just the one function, right? How would this look like?
TIA
Matt
I would use a regex, but just for the spliting :
var input = "12345_32423_131.xyz";
var output = "00000000".slice(input.split(/_|\./)[0].length)+input;
Result : "00012345_32423_131.xyz"
EDIT :
the fast, no-splitting but no-regex, solution I gave in comments :
"00000000".slice(Math.min(input.indexOf('_'), input.indexOf('.'))+1)+input
I wouldn't split at all, just replace:
"123456_r.xyz\n12345_32423_131.xyz\n1235.xyz\n237213_21_mmm.xyz".replace(/^[0-9]+/mg, function(a) {return '00000000'.slice(0, 8-a.length)+a})
There's a simple regexp to find the part of the string you want to replace, but you'll need to use a replace function to perform the action you want.
// The array with your strings
var strings = [
'123456_r.xyz',
'12345_32423_131.xyz',
'1235.xyz',
'237213_21_mmm.xyz'
];
// A function that takes a string and a desired length
function addLeadingZeros(string, desiredLength){
// ...and, while the length of the string is less than desired..
while(string.length < desiredLength){
// ...replaces is it with '0' plus itself
string = '0' + string;
}
// And returns that string
return string;
}
// So for each items in 'strings'...
for(var i = 0; i < strings.length; ++i){
// ...replace any instance of the regex (1 or more (+) integers (\d) at the start (^))...
strings[i] = strings[i].replace(/^\d+/, function replace(capturedIntegers){
// ...with the function defined above, specifying 8 as our desired length.
return addLeadingZeros(capturedIntegers, 8);
});
};
// Output to screen!
document.write(JSON.toString(strings));

Categories

Resources