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
Related
I'm trying to change a huge string into the array of chars. In other languages there is .toCharArray(). I've used split to take dots, commas an spaces from the string and make string array, but I get only separated words and don't know how to make from them a char array. or how to add another regular expression to separate word? my main goal is something else, but I need this one first. thanks
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.toLowerCase();
str = str.split(/[ ,.]+/);
You can use String#replace with regex and String#split.
arrChar = str.replace(/[', ]/g,"").split('');
Demo:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
var arrChar = str.replace(/[', ]/g,"").split('');
document.body.innerHTML = '<pre>' + JSON.stringify(arrChar, 0, 4) + '</pre>';
Add character in [] which you want to remove from string.
This will do:
var strAr = str.replace(/ /g,' ').toLowerCase().split("")
First you have to replace the , and . then you can split it:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
var strarr = str.replace(/[\s,.]+/g, "").split("");
document.querySelector('pre').innerHTML = JSON.stringify(strarr, 0, 4)
<pre></pre>
var charArray[];
for(var i = 0; i < str.length; i++) {
charArray.push(str.charAt(i));
}
Alternatively, you can simply use:
var charArray = str.split("");
I'm trying to change a huge string into the array of chars.
This will do
str = str.toLowerCase().split("");
The split() method is used to split a string into an array of
substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is
split between each character.
Note: The split() method does not change the original string.
Please read the link:
http://www.w3schools.com/jsref/jsref_split.asp
You may do it like this
var coolString,
charArray,
charArrayWithoutSpecials,
output;
coolString = "If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
// does the magic, uses string as an array to slice
charArray = Array.prototype.slice.call(coolString);
// let's do this w/o specials
charArrayWithoutSpecials = Array.prototype.slice.call(coolString.replace(/[', ]/g,""))
// printing it here
output = "<b>With special chars:</b> " + JSON.stringify(charArray);
output += "<br/><br/>";
output += "<b>With special chars:</b> " + JSON.stringify(charArrayWithoutSpecials)
document.write(output);
another way would be
[].slice.call(coolString)
I guess this is what you are looking for. Ignoring all symbols and spaces and adding all characters in to an array with lower case.
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.replace(/\W/g, '').toLowerCase().split("");
alert(str);
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);
I'm trying to insert some whitespace in a string if the string conforms to a certain format. Specifically, if the string consists of only numbers, and is exactly five characters in length, whitespace should be added between the third and fourth numbers.
Here's my test case:
function codeAddress() {
var num_regex = /^\d+$/,
input = $("#distributor-search").val(),
address = (input.match(num_regex) && input.length == 5) ? input.split('').splice(3, 0 , ' ').join() : input ;
console.log('The address is: ' + address);
return false;
}
For some reason, chaining .split(), .splice() and .join() seems to not return anything. Where am I going wrong?
split() returns an array, splice() returns the array with the removed elements and join() returns the joined array like they should.
Looks like everything goes wrong at splice(). Instead of giving the remainders, you get the removed items.
My test:
var input = '123,789';
var output = input.split(',').splice(1, 0, '456').join(',');
console.log(output); // outputs nothing, because `splice(1, 0, '456')` doesn't remove any values
You could solve this by making a prototype that uses splice's functionality, like so:
Array.prototype.isplice = function() {
var tmp = this;
Array.prototype.splice.apply(tmp, Array.prototype.isplice.arguments);
return tmp;
};
var output = input.split(',').isplice(1, 0, '456').join(',');
console.log(output); // outputs ["123", "456", "789"] as expected
As others have explained, your function didn't work because .splice() returns the removed elements, instead of the resulting array.
Try using this regex, instead:
/^(\d\d\d)(\d\d)$/
It will only match a string if it's 5 digits long, it won't modify other strings.
Examples:
var s = '123456'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123456"
var s = '1234'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "1234"
var s = '12345'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123 45"
So, in your case:
address = $("#distributor-search").val().replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
Why not just use the regex itself?
var num_regex = /^(\d\d\d)(\d\d)$/,
input = $("#distributor-search").val(),
address = input.match(num_regex);
if (address) address = address[1] + ' ' + address[2];
That regex matches a five-digit string and groups the first three and last two digits together. If the test string matches, then the .match() function returns an array with the two groups in positions 1 and 2 (position 0 being the entire match).
You can't concatenate splice with join in your case:
splice(3, 0 , ' ').join()
remember that splice returns a new array containing the removed items, not the result array.
I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.
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.