JS: determine amount of occurrences in a string - javascript

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

Related

Splitting a string based on max character length, but keep words into account

So In my program I can receive strings of all kinds of lengths and send them on their way to get translated. If those strings are of a certain character length I receive an error, so I want to check & split those strings if necessary before that. BUT I can't just split the string in the middle of a word, the words themself also need to be intact & taken into account.
So for example:
let str = "this is an input example of one sentence that contains a bit of words and must be split"
let splitStringArr = [];
// If string is larger than X (for testing make it 20) characters
if(str.length > 20) {
// Split string sentence into smaller strings, keep words intact
//...
// example of result would be
// splitStringArr = ['this is an input', 'example of one sentence' 'that contains...', '...']
// instead of ['this is an input exa' 'mple of one senten' 'ce that contains...']
}
But I'm not sure how to split a sentence and still keep into account the sentence length.
Would a solution for this be to iterate over the string, add every word to it and check every time if it is over the maximum length, otherwise start a new array index, or are there better/existing methods for this?
You can use match and lookahead and word boundaries, |.+ to take care string at the end which are less then max length at the end
let str = "this is an input example of one sentence that contains a bit of words and must be split"
console.log(str.match(/\b[\w\s]{20,}?(?=\s)|.+$/g))
Here's an example using reduce.
const str = "this is an input example of one sentence that contains a bit of words and must be split";
// Split up the string and use `reduce`
// to iterate over it
const temp = str.split(' ').reduce((acc, c) => {
// Get the number of nested arrays
const currIndex = acc.length - 1;
// Join up the last array and get its length
const currLen = acc[currIndex].join(' ').length;
// If the length of that content and the new word
// in the iteration exceeds 20 chars push the new
// word to a new array
if (currLen + c.length > 20) {
acc.push([c]);
// otherwise add it to the existing array
} else {
acc[currIndex].push(c);
}
return acc;
}, [[]]);
// Join up all the nested arrays
const out = temp.map(arr => arr.join(' '));
console.log(out);
What you are looking for is lastIndexOf
In this example, maxOkayStringLength is the max length the string can be before causing an error.
myString.lastIndexOf(/\s/,maxOkayStringLength);
-- edit --
lastIndexOf doesn't take a regex argument, but there's another post on SO that has code to do this:
Is there a version of JavaScript's String.indexOf() that allows for regular expressions?
I would suggest:
1) split string by space symbol, so we get array of words
2) starting to create string again selecting words one by one...
3) if next word makes the string exceed the maximum length we start a new string with this word
Something like this:
const splitString = (str, lineLength) => {
const arr = ['']
str.split(' ').forEach(word => {
if (arr[arr.length - 1].length + word.length > lineLength) arr.push('')
arr[arr.length - 1] += (word + ' ')
})
return arr.map(v => v.trim())
}
const str = "this is an input example of one sentence that contains a bit of words and must be split"
console.log(splitString(str, 20))

Parse strings with a regex and store the result in an array or a string

I need some help to improve my code :
I am beginner with regex system.
I would like to fecth NUMBER below in script and store it in a string or an array to moment that output "NUMBER1,NUMBER1_NUMBER2_,NUMBER2" I don't understand why, i would like jsut NUMBER at the end ;
function fetchnumber(){
extract = "";
for(picture = 1 ; picture < 5; picture++){
// get background image as a string as this :
// url('http://www.mywebsite.com/directory/image_NUMBER_.png');
var NumberOfPicture = document.getElementById(picture).style.backgroundImage ;
reg = /\_(.*)\_/;
extract += reg.exec(NumberOfPicture);
}
}
I write this small example for you. Hope this help you.
var inputString = 'http://www.mywebsite.com/directory/image_123_.png';
var imageNumber = (/image_([^_]+)_\.\w{3}$/.exec(inputString) || [,false])[1];
// so into imageNumber variable you will have a 123 or false if there is no mach
if (imageNumber) {
// here you can do something with finded
// part of text.
}
I wish you luck with the implementation.
You asked why there is [1] instead [0]. The explanation is that we need to have
the same behavior when there is no match of regex. This is quote from MDN
The exec() method executes a search for a match in a specified string.
Returns a result array, or null.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
So. If there is match for regular expression the returned array will consist
from matched string located at zero index ([0]) and with first backreference at first index [1] back references are symbols between brackets (sddsd). But if there is no match we will pass [,false] as output so we will expect the result
into first array index [1]. Try the code with different input. For example:
var inputString = 'some text some text ';
var imageNumber = (/image_([^_]+)_\.\w{3}$/.exec(inputString) || [,false])[1];
// so into imageNumber variable you will have a 123 or false if there is no mach
if (imageNumber) {
// here you can do something with finded
// part of text.
}
So .. In this case the condition will not be executed at all. I mean:
if (imageNumber) {
// here you can do something with finded
// part of text.
}

Repeat a function in Javascript with .length

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
}

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));

How can I obtain substrings from a string in javascript?

I have a string that looks like this:
var stringOriginal = "72157632110713449SomeDynamicText";
I want to separate this string into two substrings:
One substring is the first 17 digits
One substring is the rest of the string
I want these stored in two separate variables, like this:
var string1 = "72157632110713449"; //First static 17 digits
var string2 = "SomeDynamicText"; // Dynamic Text
Assuming your string is fixed, you can use the substring or substr string functions. The two are very similar:
substr(start, length) obtains a value from the start index to a specified length (or to the end, if unspecified)
substring(start, end) obtains a value from the start index to the end index (or the end, if unspecified)
So, one way you could do it by mixing and matching the two, is like this:
var string1 = stringOriginal.substring(0, 17);
# interestingly enough, this does the same in this case
var string1 = stringOriginal.substr(0, 17);
var string2 = stringOriginal.substr(17);
If, however, you need a more sophisticated solution (e.g. not a fixed length of digits), you could try using a regex:
var regex = /(\d+)(\w+)/;
var match = regex.exec(stringOriginal);
var string1 = match[1]; // Obtains match from first capture group
var string2 = match[2]; // Obtains match from second capture group
Of course, this adds to the complexity, but is more flexible.
Here you go:
string1 = stringOriginal.substring(0, 17);
string2 = stringOriginal.substring(17, stringOriginal.length);
or
string2 = stringOriginal.substring(17);
//Second parameter is optional. The index where to stop the extraction.
//If second parameter is omitted, it extracts the rest of the string
This will split the string into vars given that the first 17 characters always go into string1 and the remainder into string2.
var string1 = stringOriginal.substring(0,17);
var string2 = stringOriginal.substring(17,stringOriginal.length);
Assuming that you want to split the string by separating initial digits from the rest regardless of length :
string = string.match (/^(\d+)(.*)/) || [string, '', ''];
string[1] will hold the initial digits, string[2] the rest of the string, the original string will be in string[0].
If string does not start with a digit, string[0] will hold the original string and string[1] and string[2] will be empty strings.
By changing the code to :
string = string.match (/^(\d*)(.*)/);
strings containing no initial digits will have string[1] empty and string[2] will have the same value as string[0], i.e the initial string. In this case there is no need to handle the case of a failing match.

Categories

Resources