javascript - how to break up a string every X amount of characters? - javascript

How do I break up a string every X amount of characters? For example, I'd like to break up a very long string every 1000 characters, and the string could be completely random everytime.
var string = <my text string that is thousands of characters long>

You could use Regex:
'asdfasdfasdfasdf'.match(/.{3}|.{1,2}/g); // 'asd', 'fas', etc.
Replace 3 with 1000 of course.
Here's a contrived example: http://jsfiddle.net/ReRPz/1/
As a function:
function splitInto(str, len) {
var regex = new RegExp('.{' + len + '}|.{1,' + Number(len-1) + '}', 'g');
return str.match(regex );
}
That RegExp really only needs to be created once if you have a set number to split like 1000.

Try this function:
function getParts(str, len)
{
var res = [];
​while (str.length) {
res.push(str.substring(0, len));
str = str.substring(len);
}
return res;
}
var s = "qweasedzxcqweasdxzc12";
console.log(getParts(s, 10));
​

i would use substring function on string
str = //the given string
arr = [];
for(i=0;i<str.length;i+=1000)
{
s = i;
// if the last string is less than 1000chars
e = (str.length - i) > 1000 ? (i+1000) : (str.length - i);
arr.push = str.substring(s,e);
}

Here's a way to do it recursively:
var string = "my text string that is thousands of characters long";
var arr = [];
function div( str, len ) {
if( str.length < len )
return arr.push(str);
else
arr.push(str.substring(0,len))
div( str.substring(len), len );
}
div( string, 5 );
for( var i = 0; i < arr.length; i++ ) {
document.write( arr[i] + "<br/>");
}
/* output:
my te
xt st
ring
that
is th
ousan
ds of
char
acter
s lon
g
*/

Like this:
var myString = "my text string that is thousands of characters long";
var myCurrentString = "";
var myBrokenUpString = new Array();
for(var i = 0; i < myString.length; i++) {
myCurrentString += myString.charAt(i);
if(i % 1000 == 0) {
myBrokenUpString.push(myCurrentString);
myCurrentString = "";
}
if(i + 1 == myString.length) myBrokenUpString.push(myCurrentString);
}
Please note that the above code is untested and may contain errors.
You can then POST the array and piece it back together on the other end. The piecing-together-code would look something like this:
var myRestoredString = "";
for(var i = 0; i<myBrokenUpString.length; i++) {
myRestoredString += myBrokenUpString[i];
}

Borrowing the idea from Joe Tuskan:
var str = 'asdfasdfasdfasdf';
var len = 3;
var regex = new RegExp(".{"+len+"}", "g");
var trail = str.length - (str.length % len);
var parts = str.match(regex);
parts.push(str.substring(trail));
document.write(parts.join('<br>'));
http://jsfiddle.net/6aSHB/1/

Related

Reverse String In Place Using for loop in JavaScript

var n = "reversestrings", k=3;
want to reverse string in chunk of 'k',
Answer would be : ver sre tse nir gs;
if Last word less then 'k' then don't need to reverse.
I am using below code but not getting expected answer.
var n = 'stringreverses', k = 3, str = '', s = '';
var c = 0;
for( var i=0; i<n.length; i++ ){
if( c<k ){
c++
str += n[i];
s=str.split('').reverse().join('');
}
else{
console.log("-" + s);
c=0;
}
}
First we need to split input to chunks with the same size (the last one can be smaller), next we reverse every chunk and concatenate at the end.
var input = "123456",
chunks = input.match(new RegExp('.{1,' + k + '}', 'g'));
var result = chunks.map(function(chunk) {
return chunk.split('').reverse().join('');
}).join('');
Homework or not, here is a good use case to start with strings.
Here is a C approach but you have more in Javascript.
In fact you want to reverse by chunk so deal with chunk. How to create a chunk of string ? a way is to use slice https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/slice
var str = "abcdef";
console.log(str.slice(0,2));
So you have an easy way to slice your string into chunk.
Then you have to iterate over it, there is no good way of doing it actually there is dozen but you could do it from backward to the beginning of the string:
for( i=str.length ; i>0 ; i -= k ){
// i will go from the end of your str to
// the beginning by step of k(=3) and you can use i - k and i
// to slice your string (as we see it before)
// you have to take care of the last part that could be less than
// 3
}
then you have to format the result, the most easy way to do that is to concatenate results into a string here it is :
var strRes = "";
strRes += "res 1";
strRes += "res 2";
console.log(strRes); // should screen "res 1res 2"
As it is homework, I wont make a jsfiddle, you have here all the pieces and it's up to you to build the puzzle.
hope that help
$(function() {
var n = 'reversestrings', k = 3;
var revString = "";
for (var i =0; i<=n.length; i++) {
if (i%k == 0) {
l = parseInt(k) + parseInt(i);
var strChunk = n.substring(i,l);
var innerStr = "";
for (var j =0; j<strChunk.length; j++) {
var opp = parseInt(strChunk.length) - parseInt(j) - 1;
innerStr = innerStr + strChunk.charAt(opp);
}
revString = revString + " "+innerStr;
}
}
alert(revString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
My take on this. Pure JS without even built-in functions:
function reverseSubStr(str) {
var right = str.length - 1, reversedSubStr = '';
while(right >= 0) {
reversedSubStr += str[right];
right--;
}
return reversedSubStr;
}
function reverseStr(str) {
var initialStr = str, newstr = '', k = 3, substr = ''
for(var i = 1; i <= initialStr.length; i++) {
substr += initialStr[i - 1]; // form a substring
if(i % k == 0) { // once there are 3 symbols - reverse the substring
newstr += reverseSubStr(substr) + " "; // ... and add space
substr = ''; // then clean temp var
}
}
return newstr += substr; // add the remainder of the string - 'gs' - and return the result
}
var str = 'reversestrings';
console.log(reverseStr(str)); //ver sre tse nir gs
I like #Jozef 's approch but here is mine as well for those who are not much into Regex -
//Taking care of Tail Calling
function reverStrInChunk(str, k, r=''){
let index=0, revStr,
res = str.substring(index, k), remStr;
revStr = res.split("").reverse().join("");
remStr = str.substring(k, str.length);
r = r + revStr;
if(remStr.length>k){
return reverStrInChunk(remStr,k, r+" ");
}
else if(remStr.length<k) {
return r +" "+remStr;
}else{
return r +" "+ remStr.split("").reverse().join("");
}
}
var aStr = reverStrInChunk('reversestrings',3);//ver sre tse nir gs
console.log(aStr);

How to make characters in a string repeat using Javascript?

How can I make individual characters within a string repeat a given amount of times?
That is, how do I turn "XyZ" into "XXXyyyZZZ"?
Try this:
var foo = 'bar';
function makeString(str, repeat) {
var str = Array.prototype.map.call(str, function(character) {
var nascentStr = '';
while (nascentStr.length < repeat) {
nascentStr += character;
}
return nascentStr;
}).join('');
return str;
}
alert(makeString(foo, 3));
You'll need to use a combination of a few functions. First you'll need to split the string into individual characters:
var charArray = "XyZ".split('');
Once you have it split up, you can use a combination of the .map function and a nifty little trick of javascript Array.
var someMultiplier = 5;
var duplicatedArray = charArray.map(function(char) {
return Array(someMultiplier).join(char);
});
At that point, you have an array of strings that have the duplicate letters, and you can combine them back with .join
var dupString = duplicatedArray.join('');
dupString === "XXXXXyyyyyZZZZZ
Sounds straight forward. You can run this in your browser's console:
var my = 'XyZ';
function repeat(str, times) {
var res = '';
for (var i in str) {
var char = str[i];
for (var j=0; j < times; j++) {
res += char;
}
}
return res;
}
var his = repeat(my, 3);
console.log(his);
you have not mentioned what will happen if input will be like xyxzy. Assuming it will be xxxyyxxxzzzyyy
// function takes input string & num of repitation
function buildString(input, num) {
var _currentChar = ""; // Final output string
for (var m = 0; m < input.length; m++) {
//call another function which will return XXX or yyy or zzz & then finally concat it
_currentChar += _repeatString((input.charAt(m)), num);
}
}
// It will return XXX or yyy or ZZZ
// takes individual char as input and num of times to repeat
function _repeatString(char, num) {
var _r = "";
for (var o = 0; o < num; o++) {
_r += char;
}
return _r
}
buildString('XyZ', 3)
jsfiddle for Example
function repeatStringNumTimes(str, num) {
let valueCopy = str
if (num > 0) {
for (var i = 0; i < num - 1; i++) {
valueCopy = valueCopy.concat(str)
}
} else {
valueCopy = ""
}
return valueCopy;
}
repeatStringNumTimes("abc", 3);
These days can be done a lot easier:
const repeater = (str, n) => [...str].map(c => c.repeat(n)).join('');
alert(repeater('XyZ', 3));

JavaScript/jQuery: Split a Text up to Occurence of a Symbol Using Loop

I have a text content as follows:
var text = "asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf^..."
I want to split the text up-to multiple of 5th occurrence of ^ and pass to a function with the ^ symbol.
If there are 31 ^ in the element then: 5th, 10th, 15th, 20th, 25th, 30th and then remaining should be passed to the function (i.e. 31st with ^).
I prefer a for loop like:
var spl = text.split(); //up-to 5th multiple
for(i=0; i<spl.length; i++){
passfun(upto 5th^ with cap symbol)
}
Example:
var text = "asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf^sssad^gsds..."
passfun("asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^"); //1st time
passfun("dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf^");//2nd time
passfun("sssad^gsds");//last
Try something like this
var text = "asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf^...";
var spl = text.split('^');
Array.prototype.chunk = function ( n ) {
if ( !this.length ) {
return [];
}
return [ this.slice( 0, n ) ].concat( this.slice(n).chunk(n) );
};
console.log(spl.chunk(5)[0].join('^')+'^');
more info
Split array into chunks
demo here:
https://jsfiddle.net/bo4eacv5/1/
You can try this:
var text = "asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf",
temp = text.split('^');
for (i = 0; i < temp.length; i += 5) {
passfun(temp.slice(i, 5 + i).join('^') + ( i + 5 < temp.length ? '^' : ''));
}
Hello friend it perfect little bit may be length correction need if you have any problem then otherwise no need
var text = "asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf^split^text^upto^5th^and^..";
//I want to split the text upto multiple of 5th occurrance of ^ and
//var abc = text.split("^").length - 1;
var counter = 0, index = 0;
var temp = 0, indexArr = [];
for (var i = 0; i < text.length; i++) {
index++;
if (text.charAt(i) == '^') {
counter++;
}
if (counter == 5) {
counter = 0;
myString(index);
}
}
function myString(tempindex) {
var tempString = '';
indexArr[temp] = tempindex;
if (temp == 0) {
tempString = text.substr(0, tempindex);
passfun(tempString);
temp++;
} else {
tempString = text.substr(indexArr[temp - 1], indexArr[temp - 1]);
passfun(tempString);
temp++;
}
return;
}

Each Character occurrence in a string

How to write a javascript code that counts each character occurrence in a string ?
e.g
String is : Hello World
Output :
count of H -> 1
count of e -> 1
count of l -> 3
count of o -> 2
count of r -> 1
count of d -> 1
count of W -> 1
var counts = {};
yourstring.split('').map(function(ch) {
counts[ch] = (counts[ch] || 0) + 1;
});
Or be hip and use map/reduce:
var counts = yourstring.split('').reduce(function(dst, c) {
dst[c] = (dst[c] || 0) + 1;
return dst;
}, {});
this code should work:
var str = "Hello World";
var arr = str.split('');
var occ = {};
for(var i=0,c=arr.length;i<c;i++){
if(occ[arr[i]]) occ[arr[i]]++;
else occ[arr[i]] = 1;
}
for(var i in occ){
alert('count of '+i+' -> '+occ[i]);
}
var splitWord = "Hello World".split('');
var letters = {};
for(var i in splitWord)
{
var letter = splitWord[i];
if(letter == ' ') continue;
if(typeof letters[letter] == 'undefined')
{
letters[letter] = 0;
}
letters[letter]++;
}
console.dir(letters);
Below is my solution with the old and simple for loop. This approach answers the question in the simplest possible way for beginners.
This code will convert all the letters in the input to lower case and count their occurrence. In this solution, we also count the special characters and spaces as valid characters.
function countChar(str) {
var count = {};
for (let i = 0; i < str.length; i++) {
var ch = str[i].toLowerCase();
if (count[ch] > 0) {
count[ch]++;
} else {
count[ch] = 1;
}
}
return count;
}
The count object denotes the characters in the input.

Arrangement of two string charecters into one string using loop

I have two string which should be put together into one string. First string is a input value and second string is a pattern how the first string should look. Here is the example - Input string( var val ) - 9165678823 Patter string( var mask ) - (999)999-9999 Output string should look like( var startVal ) - (916)567-8823 I have tried working out and this is my code
var val = $(control).data("loadMaskValue"); // Input Value
var mask = $(control).attr("mask"); //Masking Pattern
var startVal = "";
var j = 0;
for (var i = 0; i < mask.length; i++) {
var c = mask.charAt(j);
if (c == '9' || c == 'X' || c == 'A') { //Checks the char is normal char
startVal += val.charAt(j);
}
else {
startVal += c; //Inserts the special char to string like ( ) -
startVal += val.charAt(j);
}
j = startVal.length;
}
The problem with this code is it misses one number in between. The result of this code is startValue - (965)688-2. PLease help me.
Here's a slightly simpler implementation:
var input = '9165678823';
var mask = '(999)999-9999';
var output = '';
var offset = 0;
for (var i = 0; i < mask.length; i++) {
var char = mask.charAt(i);
if ('9XA'.indexOf(char) != -1) {
output += input.charAt(i - offset);
} else {
output += mask.charAt(i);
offset += 1;
}
}
console.log(output);
​Make sure that input has been stripped of all whitespace at the beginning and end.
Demo: http://jsfiddle.net/qWtjk/
You can use a regular expression to take the elements out. Check the fiddle: http://jsfiddle.net/BuddhiP/9MmqS/
var str= '9165678823';
var regEx = new RegExp("(\d{3})(\d{3})(\d{4})");
var m = regEx.exec(str);
var res = '(' + m[1] + ')' + m[2] + '-' + m[3];
console.log(res);
result is (916)567-8823
UPDATE: How to make this work with a dynamic pattern. Check updated fiddle: http://jsfiddle.net/BuddhiP/9MmqS/
$(function() {
var str= '9165678823';
var regEx = new RegExp("(\\d{3})(\\d{3})(\\d{4})");
var m = regEx.exec(str);
var mask = "({0}){1}-{2}";
var res = mask.supplant(m.slice(1));
console.log(res);
});​
Using supplant method from here: http://javascript.crockford.com/remedial.html
Once you understand your regular expression, you can make this work with any pattern and mask.

Categories