Javascript How to split string by symbols count [duplicate] - javascript

As the title says, I've got a string and I want to split into segments of n characters.
For example:
var str = 'abcdefghijkl';
after some magic with n=3, it will become
var arr = ['abc','def','ghi','jkl'];
Is there a way to do this?

var str = 'abcdefghijkl';
console.log(str.match(/.{1,3}/g));
Note: Use {1,3} instead of just {3} to include the remainder for string lengths that aren't a multiple of 3, e.g:
console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"]
A couple more subtleties:
If your string may contain newlines (which you want to count as a character rather than splitting the string), then the . won't capture those. Use /[\s\S]{1,3}/ instead. (Thanks #Mike).
If your string is empty, then match() will return null when you may be expecting an empty array. Protect against this by appending || [].
So you may end up with:
var str = 'abcdef \t\r\nghijkl';
var parts = str.match(/[\s\S]{1,3}/g) || [];
console.log(parts);
console.log(''.match(/[\s\S]{1,3}/g) || []);

If you didn't want to use a regular expression...
var chunks = [];
for (var i = 0, charsLength = str.length; i < charsLength; i += 3) {
chunks.push(str.substring(i, i + 3));
}
jsFiddle.
...otherwise the regex solution is pretty good :)

str.match(/.{3}/g); // => ['abc', 'def', 'ghi', 'jkl']

Building on the previous answers to this question; the following function will split a string (str) n-number (size) of characters.
function chunk(str, size) {
return str.match(new RegExp('.{1,' + size + '}', 'g'));
}
Demo
(function() {
function chunk(str, size) {
return str.match(new RegExp('.{1,' + size + '}', 'g'));
}
var str = 'HELLO WORLD';
println('Simple binary representation:');
println(chunk(textToBin(str), 8).join('\n'));
println('\nNow for something crazy:');
println(chunk(textToHex(str, 4), 8).map(function(h) { return '0x' + h }).join(' '));
// Utiliy functions, you can ignore these.
function textToBin(text) { return textToBase(text, 2, 8); }
function textToHex(t, w) { return pad(textToBase(t,16,2), roundUp(t.length, w)*2, '00'); }
function pad(val, len, chr) { return (repeat(chr, len) + val).slice(-len); }
function print(text) { document.getElementById('out').innerHTML += (text || ''); }
function println(text) { print((text || '') + '\n'); }
function repeat(chr, n) { return new Array(n + 1).join(chr); }
function textToBase(text, radix, n) {
return text.split('').reduce(function(result, chr) {
return result + pad(chr.charCodeAt(0).toString(radix), n, '0');
}, '');
}
function roundUp(numToRound, multiple) {
if (multiple === 0) return numToRound;
var remainder = numToRound % multiple;
return remainder === 0 ? numToRound : numToRound + multiple - remainder;
}
}());
#out {
white-space: pre;
font-size: 0.8em;
}
<div id="out"></div>

If you really need to stick to .split and/or .raplace, then use /(?<=^(?:.{3})+)(?!$)/g
For .split:
var arr = str.split( /(?<=^(?:.{3})+)(?!$)/ )
// [ 'abc', 'def', 'ghi', 'jkl' ]
For .replace:
var replaced = str.replace( /(?<=^(?:.{3})+)(?!$)/g, ' || ' )
// 'abc || def || ghi || jkl'
/(?!$)/ is to not stop at end of the string. Without it's:
var arr = str.split( /(?<=^(?:.{3})+)/ )
// [ 'abc', 'def', 'ghi', 'jkl' ] // is fine
var replaced = str.replace( /(?<=^(.{3})+)/g, ' || ')
// 'abc || def || ghi || jkl || ' // not fine
Ignoring group /(?:...)/ is to prevent duplicating entries in the array. Without it's:
var arr = str.split( /(?<=^(.{3})+)(?!$)/ )
// [ 'abc', 'abc', 'def', 'abc', 'ghi', 'abc', 'jkl' ] // not fine
var replaced = str.replace( /(?<=^(.{3})+)(?!$)/g, ' || ' )
// 'abc || def || ghi || jkl' // is fine

My solution (ES6 syntax):
const source = "8d7f66a9273fc766cd66d1d";
const target = [];
for (
const array = Array.from(source);
array.length;
target.push(array.splice(0,2).join(''), 2));
We could even create a function with this:
function splitStringBySegmentLength(source, segmentLength) {
if (!segmentLength || segmentLength < 1) throw Error('Segment length must be defined and greater than/equal to 1');
const target = [];
for (
const array = Array.from(source);
array.length;
target.push(array.splice(0,segmentLength).join('')));
return target;
}
Then you can call the function easily in a reusable manner:
const source = "8d7f66a9273fc766cd66d1d";
const target = splitStringBySegmentLength(source, 2);
Cheers

const chunkStr = (str, n, acc) => {
if (str.length === 0) {
return acc
} else {
acc.push(str.substring(0, n));
return chunkStr(str.substring(n), n, acc);
}
}
const str = 'abcdefghijkl';
const splittedString = chunkStr(str, 3, []);
Clean solution without REGEX

My favorite answer is gouder hicham's. But I revised it a little so that it makes more sense to me.
let myString = "Able was I ere I saw elba";
let splitString = [];
for (let i = 0; i < myString.length; i = i + 3) {
splitString.push(myString.slice(i, i + 3));
}
console.log(splitString);
Here is a functionalized version of the code.
function stringSplitter(myString, chunkSize) {
let splitString = [];
for (let i = 0; i < myString.length; i = i + chunkSize) {
splitString.push(myString.slice(i, i + chunkSize));
}
return splitString;
}
And the function's use:
let myString = "Able was I ere I saw elba";
let mySplitString = stringSplitter(myString, 3);
console.log(mySplitString);
And it's result:
>(9) ['Abl', 'e w', 'as ', 'I e', 're ', 'I s', 'aw ', 'elb', 'a']

try this simple code and it will work like magic !
let letters = "abcabcabcabcabc";
// we defined our variable or the name whatever
let a = -3;
let finalArray = [];
for (let i = 0; i <= letters.length; i += 3) {
finalArray.push(letters.slice(a, i));
a += 3;
}
// we did the shift method cause the first element in the array will be just a string "" so we removed it
finalArray.shift();
// here the final result
console.log(finalArray);

var str = 'abcdefghijkl';
var res = str.match(/.../g)
console.log(res)
here number of dots determines how many text you want in each word.

function chunk(er){
return er.match(/.{1,75}/g).join('\n');
}
Above function is what I use for Base64 chunking. It will create a line break ever 75 characters.

Here we intersperse a string with another string every n characters:
export const intersperseString = (n: number, intersperseWith: string, str: string): string => {
let ret = str.slice(0,n), remaining = str;
while (remaining) {
let v = remaining.slice(0, n);
remaining = remaining.slice(v.length);
ret += intersperseWith + v;
}
return ret;
};
if we use the above like so:
console.log(splitString(3,'|', 'aagaegeage'));
we get:
aag|aag|aeg|eag|e
and here we do the same, but push to an array:
export const sperseString = (n: number, str: string): Array<string> => {
let ret = [], remaining = str;
while (remaining) {
let v = remaining.slice(0, n);
remaining = remaining.slice(v.length);
ret.push(v);
}
return ret;
};
and then run it:
console.log(sperseString(5, 'foobarbaztruck'));
we get:
[ 'fooba', 'rbazt', 'ruck' ]
if someone knows of a way to simplify the above code, lmk, but it should work fine for strings.

Coming a little later to the discussion but here a variation that's a little faster than the substring + array push one.
// substring + array push + end precalc
var chunks = [];
for (var i = 0, e = 3, charsLength = str.length; i < charsLength; i += 3, e += 3) {
chunks.push(str.substring(i, e));
}
Pre-calculating the end value as part of the for loop is faster than doing the inline math inside substring. I've tested it in both Firefox and Chrome and they both show speedup.
You can try it here

Here's a way to do it without regular expressions or explicit loops, although it's stretching the definition of a one liner a bit:
const input = 'abcdefghijlkm';
// Change `3` to the desired split length.
const output = input.split('').reduce((s, c) => {
let l = s.length-1;
(s[l] && s[l].length < 3) ? s[l] += c : s.push(c);
return s;
}, []);
console.log(output); // output: [ 'abc', 'def', 'ghi', 'jlk', 'm' ]
It works by splitting the string into an array of individual characters, then using Array.reduce to iterate over each character. Normally reduce would return a single value, but in this case the single value happens to be an array, and as we pass over each character we append it to the last item in that array. Once the last item in the array reaches the target length, we append a new array item.

Some clean solution without using regular expressions:
/**
* Create array with maximum chunk length = maxPartSize
* It work safe also for shorter strings than part size
**/
function convertStringToArray(str, maxPartSize){
const chunkArr = [];
let leftStr = str;
do {
chunkArr.push(leftStr.substring(0, maxPartSize));
leftStr = leftStr.substring(maxPartSize, leftStr.length);
} while (leftStr.length > 0);
return chunkArr;
};
Usage example - https://jsfiddle.net/maciejsikora/b6xppj4q/.
I also tried to compare my solution to regexp one which was chosen as right answer. Some test can be found on jsfiddle - https://jsfiddle.net/maciejsikora/2envahrk/. Tests are showing that both methods have similar performance, maybe on first look regexp solution is little bit faster, but judge it Yourself.

var b1 = "";
function myFunction(n) {
if(str.length>=3){
var a = str.substring(0,n);
b1 += a+ "\n"
str = str.substring(n,str.length)
myFunction(n)
}
else{
if(str.length>0){
b1 += str
}
console.log(b1)
}
}
myFunction(4)

function str_split(string, length = 1) {
if (0 >= length)
length = 1;
if (length == 1)
return string.split('');
var string_size = string.length;
var result = [];
for (let i = 0; i < string_size / length; i++)
result[i] = string.substr(i * length, length);
return result;
}
str_split(str, 3)
Benchmark: http://jsben.ch/HkjlU (results differ per browser)
Results (Chrome 104)

Related

Function is meant to be non-destructive but it is modifying my variable

I have the following code which sets special to run a function convertSpecial which will replace the apostrophe in array1 with a provided character. In this case, a space. Since the replacing character is a space, it will split that element into two then flatten the array. It will then check to see if any element in special matches any element in array2. This will return false. It will then replace the apostrophe with no character at all and recheck against array2.
The idea behind convertSpecial and the variable special is that it should be non-destructive to array1, but this isn't happening as you can see:
var array1 = ["o'hara"];
var array2 = ["ohara"];
var special = '';
function convertSpecial(a,b,c) {
var aCopy = a;
for (let i = 0; i < aCopy.length; i++) {
if (aCopy[i].includes(b)) {
if (c == '') {
aCopy[i] = aCopy[i].replace(b,c);
} else {
aCopy[i] = aCopy[i].replace(b,c).split(' ');
aCopy = aCopy.flat();
}
}
}
return aCopy;
}
console.log('array1 1 = '+array1); // returns array1 1 = o'hara as expected
special = convertSpecial(array1,"'"," ");
console.log('array1 2 = '+array1); // returns array1 2 = o,hara THIS SHOULD NOT HAVE BEEN MODIFIED
console.log('special 1 = '+special); //returns special 2 = o,hara as expected
if (array2.some(v => special.includes(v)) == true) {
console.log('array1 3 = '+array1); // ignored as expected
array1 = specialDECln;
} else {
console.log('array1 4 = '+array1); //returns array1 4 = o,hara THIS SHOULD NOT HAVE BEEN MODIFIED
special = convertSpecial(array1,"'","");
console.log('array1 5 = '+array1); //returns array1 5 = o,hara THIS SHOULD NOT HAVE BEEN MODIFIED
console.log('special 2= '+special); //returns special 2 = o,hara should be ohara
if (array2.some(v => special.includes(v)) == true) {
array1 = special;
}
}
console.log(array2 == special); //returns false, should be true because expected ohara = ohara
Everything works as it should, EXCEPT array1 is being modified when it shouldn't be at all. Since it gets modified, special gets set to an incorrect value.
What am I doing wrong and how can I fix it?
You need to clone that array in order to avoid mutation. There are a lot of ways for doing that, an alternative is using the Spread-syntax as follow:
let result = [...a]; // This creates a new array with the index-values from array a.
var array1 = ["o'hara"];
var special = ''
console.log("array1 = " + array1); // returns array1 = o'hara as expected
function convertSpecial(a, b, c) { // a = array, b = character to replace, c = character to replace with
let result = [...a];
for (let i = 0; i < result.length; i++) {
if (result[i].includes(b)) {
if (c == '') {
result[i] = result[i].replace(b, c);
} else {
result[i] = result[i].replace(b, c).split(' ');
result = result.flat();
}
}
}
return result;
}
special = convertSpecial(array1, "'", " ");
console.log("array1 = " + array1); // returns array1 = o, hara but it should be o'hara
console.log("special = " + special); // returns special = o, hara as expected
You need to duplicate the array first:
var array1 = ["o'hara"];
var special = ''
console.log("array1 = " + array1); // returns array1 = o'hara as expected
function convertSpecial(a, b, c) { // a = array, b = character to replace, c = character to replace with
var aCopy = a.slice();
for (let i = 0; i < aCopy.length; i++) {
if (aCopy[i].includes(b)) {
if (c == '') {
aCopy[i] = aCopy[i].replace(b, c);
} else {
aCopy[i] = aCopy[i].replace(b, c).split(' ');
aCopy = aCopy.flat();
}
}
}
return aCopy;
}
special = convertSpecial(array1, "'", " ");
console.log("array1 = " + array1); // returns array1 = o, hara but it should be o'hara
console.log("special = " + special); // returns special = o, hara as expected

How to count words from window.prompt and sort them by number of apperance?

I need to count words from prompt and write them to the array. Next I have to count their appearance and sort them.
I have code like this:
let a = window.prompt("Write sentence")
a = a.split(" ")
console.log(a)
var i = 0;
for (let i = 0; i < a.length; i++) {
a[i].toUpperCase;
let res = a[i].replace(",", "").replace(".", "")
var count = {};
a.forEach(function(i) {
count[i] = (count[i] || 0) + 1;
});
console.log(count);
document.write(res + "<br>")
}
I don't know how to connect my word with specific number for number of appearances and write this words one time.
On the end it should look like:
a = "This sentence, this stentence, this sentence, nice."
This - 3
Sentence - 3
nice - 1
If I don't misunderstood your requirements then Array.prototype.reduce() and Array.prototype.sort() will the trick for you. Imagine I got the example string from your window.prompt()
let string = `this constructor doesn't have neither a toString nor a valueOf. Both toString and valueOf are missing`;
let array = string.split(' ');
//console.log(array);
let result = array.reduce((obj, word) => {
++obj[word] || (obj[word] = 1); // OR obj[word] = (++obj[word] || 1);
return obj;
}, {});
sorted_result = Object.keys(result).sort(function(a,b){return result[a]-result[b]})
console.log(result);
console.log(sorted_result);
AS PER QUESTION EDIT
let string = `This sentence, this sentence, this sentence, nice.`;
let array = string.split(' ');
array = array.map(v => v.toLowerCase().replace(/[.,\s]/g, ''))
let result = array.reduce((obj, word) => {
++obj[word] || (obj[word] = 1); // OR obj[word] = (++obj[word] || 1);
return obj;
}, {});
console.log(result)
You can use reduce. Like so:
const wordsArray = [...].map(w => w.toLowerCase());
const wordsOcurrenceObj = wordsAray.reduce((acc, word) => {
if (!acc[word]) {
acc[word] = 0;
}
acc[word] += 1;
return acc;
}, {});
What this does is keep track of the words in an object. When a word is not there, initializes with zero. And then adds a 1 every time you encounter that word. You will end up with an object like this:
{
'word': 3,
'other': 1,
...
}
Add another loop at the end that goes over the counts and prints them:
for(let word in count) {
console.log(word + " appeared " + count[word] + " times");
}

Merge strings in javascript

I want to merge two variable with stings alternately using javascript. What would be an algorithm to accomplish this task?
For example:
var a = "abc"
var b = "def"
result = "adbecf"
I would use Array.from to generate an array from the strings (unicode conscious).
After that, just add a letter from each string until there's no letters left in each. Please note this solution will combine strings of uneven length (aa+bbbb=ababbb)
var a = "abc"
var b = "def"
var d = "foo 𝌆 bar mañana mañana"
function combineStrings(a,b){
var c = "";
a = Array.from(a);
b = Array.from(b);
while(a.length > 0 || b.length > 0){
if(a.length > 0)
c += a.splice(0,1);
if(b.length > 0)
c += b.splice(0,1);
}
return c;
}
var test = combineStrings(a,b);
console.log(test);
var test2 = combineStrings(a,d);
console.log(test2);
The best way to do this is to perform the following algorithm:
Iterate through string 1
For each character, if there is a character in the same position in string 2, replace the original character with both
This can be achieved with the following code:
function merge(s, t) {
return s.split("")
.map(function(v,i) {
return t[i] ? v + t[i] : v
})
.join("")
}
or the more Codegolf type answer:
s=>t=>[...s].map((v,i)=>t[i]?v+t[i]:v).join``
The simple way would be define the longest string and assigned to for loop. Also you have to add if statments for strings of uneven length, because you want to ignore undefined values of shorter string.
function mergeStrings(s1, s2){
var n = s1.length;
if(s1.length < s2.length){
n = s2.length;
}
var string = '';
for(var i = 0; i < n; i++){
if(s1[i]){
string += s1[i];
}
if(s2[i]){
string += s2[i];
}
}
return string;
}
console.log(mergeStrings('ab','lmnap'));
console.log(mergeStrings('abc','def'));
If your strings are the same length, this will work. If not you'll have to append the rest of the longer string after the loop. You can declare i outside of the loop and then use substr() to get the end of the longer string.
const a = "abc"
const b = "def"
var res = "";
for (var i = 0;i < Math.min(a.length, b.length); i++) {
res += a.charAt(i) + b.charAt(i)
}
console.log(res)
Regex or array processing and joining do the job:
let a = 'abc';
let b = 'def';
console.log(a.replace(/./g, (c, i) => c + b[i])); // 'adbecf'
console.log(Array.from(a, (c, i) => c + b[i]).join('')); // 'adbecf'
You can solve this using array spread and reduce. Split each string into an array and merge into one array and then use reduce to generate the merged string.
function mergeStrings(a, b) {
const mergedValues = [
...a.split(''),
...b.split('')
].reduce((values, currentValue) => {
if (!values.includes(currentValue)) {
values.push(currentValue);
}
return values;
}, []);
return Array.from(mergedValues).join('');
}

how to cut a string in javascript

I'm receiving a String like this:
"45,21,555,64,94,796,488,\n " the \n means new line
is there a way to cut the string based on "," and getting only the "number".
I could do it C but how can I search for a character in JavaScript.
thanks for any hint
var parts = "45,21,555,64,94,796,488,\n ".split(',').filter(function(val) {
var num = parseInt(val, 10);
return !isNaN(num) && toString.call(num) === '[object Number]';
});
// parts: ["45", "21", "555", "64", "94", "796", "488"]
This is taking your String and splitting it into an Array based on a delimiter (',') and then running it through a filter function to remove anything that does not evaluate to a valid Number.
See String.prototype.split and Array.prototype.filter.
If you actually want to then convert those values to Numbers, you could chain a map call:
var parts = "45,21,555,64,94,796,488,\n ".split(',')
.filter(function(val) {
var num = parseInt(val, 10);
return !isNaN(num) && toString.call(num) === '[object Number]';
})
.map(function(val) {
return parseInt(val, 10);
});
// parts: [45, 21, 555, 64, 94, 796, 488]
Yes, like this:
var myString = "45,21,555,64,94,796,488,\n ";
var splitStrings = string.split(",");
console.log(splitStrings); //Should log an array to the console, containing only your strings e.g. [45,21,555,64,94,796,488,\n]
This returns an array of strings, split by the character you passed in. You can read more on this method here: http://www.w3schools.com/jsref/jsref_split.asp
After that, you can parse your array to remove anything you don't want like the new line character, or use a filter method to do it inline as detailed in another answer
You can use string.split(splitChar) to split. Then you can use .map or .filter to convert items to number.
var str = "45,21,555,64,94,796,488,\n ";
var arr = str.split(",");
document.write("Array: <pre>"+JSON.stringify(arr)+"</pre>");
var nums = arr.map(function(item){
return parseInt(item);
});
document.write("Numbers: <pre>"+JSON.stringify(nums)+"</pre>");
If you are wanting just the numbers as an array you could do this.
var str = "45,21,555,64,94,796,488,\n ";
var arr = str.split(","); //Make the string into an array
var len = arr.length;
for(var i=0;i<len;i++)
{
try
{
arr[i] = parseInt(arr[i]); // convert the numbers to ints
}
catch(e)
{
arr[i] = null;
}
}
As the fact that strings are just arrays, you can do it this way (a bit more comprehensive, in my opinion):
function noCommas(a)
{
var b = '';
for (var i = 0; i < a.length; i++)
{
if (a[i] != ',') //&& a[i]!= String.fromCharCode(10)) If you want no new lines too
{
b += a[i];
} else
{
//break; -> In case you only want the first value
}
}
return parseInt(b); //To return the value as an integer
}
noCommas('1234,6789'); // returns 12346789
I missunderstood the question, so here's my fixed code:
function noCommas(a)
{
var b = [];
var tempNum = '';
for (var i = 0; i < a.length; i++)
{
if (a[i] != ',' && i != a.length - 1)
{
tempNum += a[i];
} else
{
b.push(parseInt(tempNum))
tempNum = '';
}
}
return b;
}
now if you do noCommas('123,345,324234')[2] it would return 324234.

Spliting string twice with 2 separators in javascript

Let's say I need to split the string a.b.c.d#.e.f.g.h#.i.j.k.l with separator as # and then ".".
str = a.b.c.d#.e.f.g.h#.i.j.k.l
res = str.split("#")
res[0] will store a.b.c.d when I use split for the 1st time .
I need to split this again and save the data.
can anyone help ?
I think the simplest way to do it is using a regex:
var str = "a.b.c.d#.e.f.g.h#.i.j.k.l";
var res = str.split(/[.#]/);
If I may, if you have to split a string with character a then character b, the simplest in my mind would be : string.split('a').join('b').split('b')
I know this post is a bit old, but came across it, and fell like there was a better, perhaps more modern, solution. Excluding comments, this is a neat solution to this problem, and is a bit more flexible. It uses the reduce prototype, which works pretty well. This can be modified to output an object with key/value pairs as well.
const input = 'a.b.c#.e.f.g#.h.i.j'
const firstDelimiter = '#';
const secondDelimiter = '.';
// This will prevent sub arrays from containing empty values, i.e. ['','e','f','g']
const cleanInput = input.replace(/#./g, '#');
//First split by the firstDelimiter
const output = cleanInput.split(firstDelimiter).reduce( (newArr, element, i) => {
// By this point, you will have an array like ['a.b.c', 'e.f.g', 'h.i.j']
// Each element is passed into the callback, into the element variable
let subArr = element.split(secondDelimiter); // split that element by the second delimiter, created another array like ['a', 'b', 'c'], etc.
console.log(i, newArr)
// newArr is the accumulator, and will maintain it's values
newArr[i] = subArr;
return newArr;
}, []); //It's important to include the [] for the initial value of the accumulator
console.log('final:', output);
If you want to split by '#' and then for each item split by '.'
Input:'a.b.c.d#.e.f.g.h#.i.j.k'
Output:[ a b c d e f g h i j k]
var str = 'a.b.c.d#.e.f.g.h#.i.j.k.l';
var ar = [];
var sp = str.split('#');
for (var i = 0; i < sp.length; i++) {
var sub = sp[i].split('.');
for (var j = 0; j < sub.length; j++) {
ar.push(sub[j]);
}
}
alert(ar);
Here's a function I made that splits an array:
function splitArray(array, delimiter) {
let returnValue = [];
for(let i = 0; i < array.length; i++) {
array[i] = array[i].split(delimiter);
array[i].forEach(elem => {
returnValue.push(elem);
});
};
return returnValue;
};
In your case, use it like this:
str = "a.b.c.d#.e.f.g.h#.i.j.k.l";
console.log( splitArray (str.split ("#"), "." ) );
You can use the explode function similar to php
// example 1: explode(' ', 'Kevin van Zonneveld');
// returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
function explode(delimiter, string, limit) {
// discuss at: http://phpjs.org/functions/explode/
// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
if (arguments.length < 2 || typeof delimiter === 'undefined' || typeof string === 'undefined') return null;
if (delimiter === '' || delimiter === false || delimiter === null) return false;
if (typeof delimiter === 'function' || typeof delimiter === 'object' || typeof string === 'function' || typeof string ===
'object') {
return {
0: ''
};
}
if (delimiter === true) delimiter = '1';
// Here we go...
delimiter += '';
string += '';
var s = string.split(delimiter);
if (typeof limit === 'undefined') return s;
// Support for limit
if (limit === 0) limit = 1;
// Positive limit
if (limit > 0) {
if (limit >= s.length) return s;
return s.slice(0, limit - 1)
.concat([s.slice(limit - 1)
.join(delimiter)
]);
}
// Negative limit
if (-limit >= s.length) return [];
s.splice(s.length + limit);
return s;
}
For more functions visit http://phpjs.org/

Categories