How to split the string in to different parts - javascript

I want to split the string in to different parts. I will have some string which will be generated dynamically which will contains 500 characters. I want to split in to 5 parts. What i mean is i want to take 100 characters in to array[0], next 100 characters in array[1] ....
Example:
var string = "kjfaorj.......................................................";
array[0] = "kjfaorj..... up to 100 characters";
array[1] = " next 100 characters ";
..........................
..........................

if(str.length % 100 == 0) //If the string contains exactly 500 or 400...etc
count = str.length / 100;
else
count = str.length / 100 +1; //If the string contains exactly 505 or 417...etc
for(var i=0;i<count;i++)
array[i] = s.substring(i*100,(i*100)+(100));
Second approach is good for dynamic string

Try this:
var string= "kjfaorj.......................................................";
var array=[];
array[0] = string.substring(0,99);
array[1] = string.substring(100,199);
array[2] = string.substring(200,299);
array[3] = string.substring(300,399);
array[4] = string.substring(400,499);

The following loop will split up any string in pieces of 100 characters. The last element of the array will contain the remaining number of characters (but never more than 100).
If you’re certain your initial string will contain exactly 500 characters, you’ll always get an array of five elements, each one containing 100 characters.
var str = "kjfaorj....................................................... etc.";
for(var arr = [], i = 0; i < str.length - 1; i += 100) {
arr.push(str.substr(i, 100));
}
The difference between substr and substring is that substr expects the length of the substring, whereas substring expects the first and the last index.

As i see "jquery" tag in your question,i want to introduce my powerful JQuery Plugin .
Its String As JQuery
one of features of this plugin is to convert a String to Array : Each n consecutives characters of String is an item in this Array.
Syntax
var myarray=$(myString).toStrArray(eachN);
for you case , you can use it as following ;
var string = "kjfaorj.......................................................";
var myarray=$(string).toStrArray(100);
Demo
http://jsfiddle.net/abdennour/E8LhJ/

Here's a more generic function for any string length:
function splitupString(str,chunklen){
str = str.split('');
var chunks = Array((str.length/chunklen)^0).join(',').split(',');
return chunks
.map(function(){return this.splice(0,chunklen).join('');},str)
.concat(str.join(''));
}
// usage example
var strsplitted = splitupString('123456789012345678901234567890123',5);
//=> [12345,67890,12345,67890,12345,67890,123]
jsFiddle example

If you need to split the string to exactly 100 characters chunks then
var foo = bar.match(/.{100}/g);
If you need to split to chunks having no more than 100 characters, then
var foo = bar.match(/.{1,100}/g);

Related

Find out number of numbers present in a comma separated string of numbers in Javascript

I have a requirement to check if some given numbers are Pythogorean triplets.
The textbox accepts string of numbers in the below format:
3,4,5 (comma separated values)
If the user enters more than or three numbers an error alert is displayed. My team mate figure out a way to do this , but accidentally. How does the below method work?
function CheckNumbers(strnum){
var num = strnum.split(",")
if(num.length != 3)
{
alert(Enter exactly three numbers!)
return;
}
}
Should'nt it return the length of the string rather than the number of numbers?
As I read it, the input parameter strnum gets split by "," into an array, and num.length returns the length of the array.
No, The above code is right what it does is to break string in to an array and than return the length of that array
strnum = 1,2,3;
num = strnum.split(",") // num = [1,2,3]
num.length // 3
Your case is you are using a Number, and replace is associated to String.
Try to cast it before.
strnum = "1,2,3";
num = strnum.split(",") // num = [1,2,3]
num.length // 3

Javascript all words are 3 characters or longer

Let say I have a string = 'all these words are three characters orr longer'
I want to check it
if (string.someWayToCheckAllWordsAre3CharactersOrLonger) {
alert("it's valid!");
}
How can I do that?
Split the string into an array, then check if each word is longer than 3 characters using every.
var string = 'all these words are three characters orr longer';
// Using regex \s+ to split the string, so only words are get in the array
string.trim().split(/\s+/).every(e => e.length >= 3);
You can use every
Before you can use every the string need to be pre-processed.
trim the string, remove the leading and trailing spaces.
split the string by one or more space characters
Then use every to check if length every element of the array is greater than or equal to three.
Demo
var string = 'all these words are three characters orr longer';
string.trim().split(/\s+/).every(function(e) { return e.length >= 3; });
how about something like this
var string = "all these words are three characters orr longer";
var words = string.split(' ');
var allWordsAreLongerThanThreeChars = true;
for(var i=0;i<words.length;i++){
if(words[i].length < 3){
allWordsAreLongerThanThreeChars = false;
return;
}
}
Two simple steps: split string into an array using .split(), loop through the array and check the length of each word using .length(). Hope this helps.
var string = 'all these words are three characters orr longer';
var stringArray = string.split(" ");
for (var i = 0; i < stringArray.length; i++){
if(stringArray[i].length >= 3) {
alert(stringArray[i]);
}
};

how to split a string in two strings in javascript?

I have a string with a lot of characters. I would like to split the string into 2 sub-strings. I don't need to use getfirsthalf() and getsecondhalf(), but that is the idea of what i need to achieve.
var compleet = "This is the string with a lot of characters";
var part1 = compleet.getFirstHalf();
var part2 = compleet.getSecondHalf()
//output
var part1 = "This is the string wi";
var part2 = "th a lot of characters";
You can use substring() with the length of the string to divide the string in two parts by using the index.
The substring() method returns a subset of a string between one index and another, or through the end of the string.
var compleet = "This is the string with a lot of characters";
var len = compleet.length;
var firstHalf = compleet.substring(0, len / 2);
var secondHalf = compleet.substring(len / 2);
document.write(firstHalf);
document.write('<br />');
document.write(secondHalf);
You can also use substr()
You must to be more specific in your questions. But here you are a simply solution:
var str = "an string so long with the characters you need";
var strLength = str.length;
console.log(str.substring(0 , (strLength / 2));
console.log(str.substring((strLength / 2));
Assuming that when you say 'half' a string, you actually mean that two separate strings are returned containing half of the original string's characters each, you could write a prototype function to handle that as follows:
String.prototype.splitInHalf = function()
{
var len = this.length,
first = Math.ceil( len / 2 );
return [
this.substring(0, first),
this.substring(first)
];
}
When called as compleet.splitInHalf(), This function will return an array containing the two halves, as follows:
["This is the string wit", "h a lot of characters"]
Since we use Math.ceil() here, the prototype will also favour the first half of the string. For example, given a string that has an odd number of characters, such as This is, the returned array will contain 4 characters in the first string, and 3 in the second, as follows:
["This", " is"]
jsFiddle Demo

Get the Digits From a String Before and After Special Character using regex

I have a string like
5|10|20|200|300
and i want to get the First Digit Before | and last digit after | that is 5 and 300.
How would I use regex in javascript to return that numbers??
This simplest regex will return the two matches 5 and 300:
^\d+|\d+$
See the matches in the demo.
In JS:
result = yourString.match(/^\d+|\d+$/g);
Explanation
^\d+ matches the beginning of the string and some digits (the 5)
OR |
\d+$ matches some digits and the end of the string
JavaScript only keeps the last capture for (...)+, so you can write
var m = "5|10|20|200|300".match(/(\d+)(\|(\d+))+/);
Then m[1] is "5" and m[3] is "300"
var string = '5|10|20|200|300';
var array = string.split('|');
//array[0] = '5';
//array[array.length-1] = '300';
It's not regex I know, but I've always found split easier to work with in most cases.
Convert the string into an array using split() method
var str="5|10|20|200|300";
var res_array = str.split("|");
now to get first and last value of an array:::
alert("First value is"+ res_array[0]);
alert("Last value is"+ res_array[arr.length - 1]);

Separate character and number in javascript

I have one string which contain number and character. I need to separate number and character. I have don't have a delimiter in between. How can I do this.
Var selectedRow = "E0";
I need to "0" in another variable.
Help me on this.
Depends on the format of the selected row, if it is always the format 1char1number (E0,E1....E34) then you can do:
var row = "E0";
var rowChar = row.substring(0, 1);
// Number var is string format, use parseInt() if you need to do any maths on it
var number = row.substring(1, row.length);
//var number = parseInt(row.substring(1, row.length));
If however you can have more than 1 character, for example (E0,E34,EC5,EDD123) then you can use regular expressions to match the numeric and alpha parts of the string, or loop each character in the string.
var m = /\D+(\d+)/gi.exec(selectedRow);
var row = m.length == 2 ? m[1] : -1;
selectedRow.charAt(1)
Becomes more complex if your example is something longer than 'E0', obviously.

Categories