Split string suing combination of string and length - javascript

I have a string like below, which i want to split using a number and "+", i tried with the below code,
Input String:
20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407+20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085+20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054+20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345+20346+20348+20349+20355+20356.A
Code:
First found the len of the string,
var str1 = 20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407+20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085+20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054+20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345+20346+20348+20349+20355+20356.A
str2 = str1.length;
if (str2 > '400') {
var str3 = str1.split("+", 100);
}else{
var str3 = str1
}
Desired Output:
str3[0] = 20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407
str3[1] = 20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085
str3[2] = 20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054
str3[3] = 20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345
str3[4] = 20346+20348+20349+20355+20356.A
Length by default here is 100 and which should decrease based on the string rather than increasing (help need to accomplish this)
Please help me on this with some guidance

Almost the same as Nina Scholz's answer, but a little different. Starts from 0 then looks for the "+" after the next 100 characters then copies that to the result array. Starts again from the character after the "+" until the string is exhausted.
var s = '20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407+20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085+20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054+20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345+20346+20348+20349+20355+20356.A';
var start = 0,
min = 100,
pos = 0,
result = [];
while (pos != -1) {
pos = s.indexOf('+', start + min);
result.push(s.substring(start, pos == -1? s.length : pos));
start = pos+1;
}
console.log(result);

You could use String#indexOf with a right start value as fromIndex to search for the next + and slice the string for the parts.
var string = '20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407+20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085+20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054+20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345+20346+20348+20349+20355+20356.A',
length = 100,
start = 0,
pos,
result = [];
while ((pos = string.indexOf('+', start + length)) !== -1) {
result.push(string.slice(start, pos));
start = pos + 1;
}
result.push(string.slice(start));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Is this what you are looking for explanation in comments
var s = "20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407+20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085+20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054+20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345+20346+20348+20349+20355+20356.A"
var d = [];
var slug = 100;//threshold value for separatuion
var rounds = Math.ceil(s.length/slug); //find how many elemnts shall be formed
console.log(rounds);
for(var i=0;i<rounds;i++){ //loop it
d.push(s.substr(0,slug)); //extract the basic initial string
//console.log(d,s,s.length) //extract the remaining string for next iteration
s = (s.length > slug) ? s.substr(slug) : s //make sure for last string less than slug value
}
console.log(d,d.length);

Related

How do I match the numbers sequence rising?

I have a string contains just numbers. Something like this:
var numb = "5136789431235";
And I'm trying to match ascending numbers which are two or more digits. In string above I want this output:
var numb = "5136789431235";
// ^^^^ ^^^
Actually I can match a number which has two or more digits: /[0-9]{2,}/g, But I don't know how can I detect being ascending?
To match consecutive numbers like 123:
(?:(?=01|12|23|34|45|56|67|78|89)\d)+\d
RegEx Demo
To match nonconsecutive numbers like 137:
(?:(?=0[1-9]|1[2-9]|2[3-9]|3[4-9]|4[5-9]|5[6-9]|6[7-9]|7[8-9]|89)\d)+\d
RegEx Demo
Here is an example:
var numb = "5136789431235";
/* The output of consecutive version: 6789,123
The output of nonconsecutive version: 136789,1234
*/
You could do this by simply testing for
01|12|23|34|45|56|67|78|89
Regards
You just need to loop through each number and check next one. Then add that pair of values to a result variable:
var numb = "5136789431235";
var res = [];
for (var i = 0, len = numb.length; i < len-1; i++) {
if (numb[i] < numb[i+1]) res.push(new Array(numb[i],numb[i+1]))
}
res.forEach(function(k){console.log(k)});
Here is fiddle
Try this to match consecutive numbers
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
DEMO
var numb = "5136789431235";
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
document.body.innerHTML += JSON.stringify(matches,0,4);
Do you have to use Regex?
Not sure if the most efficient, but since they're always going to be numbers, could you split them up into an array of numbers, and then do an algorithm on that to sort through?
So like
var str = "123456";
var res = str.split("");
// res would equal 1,2,3,4,5,6
// Here do matching algorithm
Not sure if this is a bad way of doing it, just another option to think about
I've did something different on a fork from jquery.pwstrength.bootstrap plugin, using substring method.
https://github.com/andredurao/jquery.pwstrength.bootstrap/commit/614ddf156c2edd974da60a70d4945a1e05ff9d8d
I've created a string containing the sequence ("123456789") and scanned the sequence on a sliding window of size 3.
On each scan iteration I check for a substring of the window on the string:
var numb = "5136789431235";
//check for substring on 1st window => "123""
"5136789431235"
ˆˆˆ

How to get numbers from string in Javascript?

I have a strings that can look like this:
left 10 top 50
How can i extract the numbers, while the numbers can range from 0 to 100 and words can be left/right top/bottom? Thanks
Try match()
var text = "top 50 right 100 left 33";
var arr = text.match(/[0-9]{1,3}/g);
console.log(arr); //Returns an array with "50", "100", "33"
You can also use [\d+] (digits) instead of [0-9]
Place this string in a var, if you know every number will be seperated by a space you can easely do the following:
var string = "top 50 left 100";
// split at the empty space
string.split(" ");
var numbers = new Array();
// run through the array
for(var i = 0; i < string.length; i++){
// check if the string is a number
if(parseInt(string[i], 10)){
// add the number to the results
numbers.push(string[i]);
}
}
Now you can wrap the whole bit in a function to run it at any time you want:
function extractNumbers(string){
var temp = string.split(" ");
var numbers = new Array();
for(var i = 0; i < temp.length; i++){
if(parseInt(temp[i], 10)){
numbers.push(temp[i]);
}
}
return numbers;
}
var myNumbers = extractNumbers("top 50 left 100");
Update
After reading #AmirPopovich s answer, it helped me to improve it a bit more:
if(!isNaN(Number(string[i]))){
numbers.push(Number(string[i]));
}
This will return any type of number, not just Integers. Then you could technically extend the string prototype to extract numbers from any string:
String.prototype.extractNumbers = function(){ /*The rest of the function body here, replacing the keyword 'string' with 'this' */ };
Now you can do var result = "top 50 right 100".extractNumbers();
Split and extract the 2nd and 4th tokens:
var arr = "left 10 top 50".split(" ");
var a = +arr[1];
var b = +arr[3];
var str = 'left 10 top 50';
var splitted = str.split(' ');
var arr = [];
for(var i = 0 ; i < splitted.length ; i++)
{
var num = Number(splitted[i]);
if(!isNaN(num) && num >= 0 && num <= 100){
arr.push(num);
}
}
console.log(arr);
JSFIDDLE
If you want it dynamically by different keywords try something like this:
var testString = "left 10 top 50";
var result = getNumber("top", testString);
function getNumber(keyword, testString) {
var tmpString = testString;
var tmpKeyword = keyword;
tmpString = tmpString.split(tmpKeyword + " ");
tmpString = tmpString[1].split(' ')[0];
return tmpString;
}
var myArray = "left 10 top 50".split(" ");
var numbers;
for ( var index = 0; index < myArray.length; index++ ) {
if ( !isNaN(myArray[index]))
numbers= myArray[index]
}
find working example on the link below
http://jsfiddle.net/shouvik1990/cnrbv485/

Check how many times a string is inside a string

I got this string:
var longText="This is a superuser test, super user is is super important!";
I want to know how many times the string "su" is in longText and the position of each "su".
I was trying with:
var nr4 = longText.replace("su", "").length;
And the difference of lenght between the main text and the nr4 divided by "su" lenght beeing 2 is resulting a number of repetitions but i bet there is a better way of doing it.
For example
var parts=longText.split("su");
alert(parts.length-1); // length will be two if there is one "su"
More details using exec
FIDDLE
var re =/su/g, pos=[];
while ((result = re.exec(longText)) !== null) {
pos.push(result.index);
}
if (pos.length>0) alert(pos.length+" found at "+pos.join(","));
Use exec. Example amended from the MDN code. len contains the number of times su appears.
var myRe = /su/g;
var str = "This is a superuser test, super user is is super important!";
var myArray, len = 0;
while ((myArray = myRe.exec(str)) !== null) {
len++;
var msg = "Found " + myArray[0] + ". ";
msg += "Next match starts at " + myRe.lastIndex;
console.log(msg, len);
}
// "Found su. Next match starts at 12" 1
// "Found su. Next match starts at 28" 2
// "Found su. Next match starts at 45" 3
DEMO
Could do :
var indexesOf = function(baseString, strToMatch){
var baseStr = new String(baseString);
var wordLen = strToMatch.length;
var listSu = [];
// Number of strToMatch occurences
var nb = baseStr.split(strToMatch).length - 1;
for (var i = 0, len = nb; i < len; i++){
var ioF = baseStr.indexOf(strToMatch);
baseStr = baseStr.slice(ioF + wordLen, baseStr.length);
if (i > 0){
ioF = ioF + listSu[i-1] + wordLen;
}
listSu.push(ioF);
}
return listSu;
}
indexesOf("This is a superuser test, super user is is super important!","su");
return [10, 26, 43]
var longText="This is a superuser test, super user is is super important!";
var count = 0;
while(longText.indexOf("su") != -1) { // NB the indexOf() method is case sensitive!
longText = longText.replace("su",""); //replace first occurence of 'su' with a void string
count++;
}

for loop string each word

if this type character '這' = NonEnglish each will take up 2 word space, and English will take up 1 word space, Max length limit is 10 word space; How to get the first 10 space.
for below example how to get the result This這 is?
I'm trying to use for loop from first word but I don't know how to get each word in string...
string = "This這 is是 English中文 …";
var NonEnglish = "[^\u0000-\u0080]+",
Pattern = new RegExp(NonEnglish),
MaxLength = 10,
Ratio = 2;
If you mean you want to get that part of the string where it's length has reached 10, here's the answer:
var string = "This這 is是 English中文 …";
function check(string){
// Length of A-Za-z characters is 1, and other characters which OP wants is 2
var length = i = 0, len = string.length;
// you can iterate over strings just as like arrays
for(;i < len; i++){
// if the character is what the OP wants, add 2, else 1
length += /\u0000-\u0080/.test(string[i]) ? 2 : 1;
// if length is >= 10, come out of loop
if(length >= 10) break;
}
// return string from the first letter till the index where we aborted the for loop
return string.substr(0, i);
}
alert(check(string));
Live Demo
EDIT 1:
Replaced .match with .test. The former returns a whole array while the latter simply returns true or false.
Improved RegEx. Since we are checking only one character, no need for ^ and + that were before.
Replaced len with string.length. Here's why.
I'd suggest something along the following lines (assuming that you're trying to break the string up into snippets that are <= 10 bytes in length):
string = "This這 is是 English中文 …";
function byteCount(text) {
//get the number of bytes consumed by a string
return encodeURI(text).split(/%..|./).length - 1;
}
function tokenize(text, targetLen) {
//break a string up into snippets that are <= to our target length
var result = [];
var pos = 0;
var current = "";
while (pos < text.length) {
var next = current + text.charAt(pos);
if (byteCount(next) > targetLen) {
result.push(current);
current = "";
pos--;
}
else if (byteCount(next) == targetLen) {
result.push(next);
current = "";
}
else {
current = next;
}
pos++;
}
if (current != "") {
result.push(current);
}
return result;
};
console.log(tokenize(string, 10));
http://jsfiddle.net/5pc6L/

Adding commas, decimal to number output javascript

I'm using the following code to count up from a starting number. What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits.
function createCounter(elementId,start,end,totalTime,callback)
{
var jTarget=jQuery("#"+elementId);
var interval=totalTime/(end-start);
var intervalId;
var current=start;
var f=function(){
jTarget.text(current);
if(current==end)
{
clearInterval(intervalId);
if(callback)
{
callback();
}
}
++current;
}
intervalId=setInterval(f,interval);
f();
}
jQuery(document).ready(function(){
createCounter("counter",12714086+'',9999999999,10000000000000,function(){
alert("finished")
})
})
Executed here: http://jsfiddle.net/blackessej/TT8BH/3/
var s = 121221;
Use the function insertDecimalPoints(s.toFixed(2));
and you get 1,212.21
function insertDecimalPoints(s) {
var l = s.length;
var res = ""+s[0];
console.log(res);
for (var i=1;i<l-1;i++)
{
if ((l-i)%3==0)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res = res.replace(',.','.');
return res;
}
Check out this page for explanations on slice(), split(), and substring(), as well as other String Object functions.
var num = 3874923.12 + ''; //converts to a string
numArray = num.split('.'); //numArray[0] = 3874923 | numArray[1] = 12;
commaNumber = '';
i = numArray[0].length;
do
{
//we don't want to start slicing from a negative number. The following line sets sliceStart to 0 if i < 0. Otherwise, sliceStart = i
sliceStart = (i-3 >= 0) ? i-3 : 0;
//we're slicing from the right side of numArray[0] because i = the length of the numArray[0] string.
var setOf3 = numArray[0].slice(sliceStart, i);
commaNumber = setOf3 + ',' + commaNumber; //prepend the new setOf3 in front, along with that comma you want
i -= 3; //decrement i by 3 so that the next iteration of the loop slices the next set of 3 numbers
}
while(i >= 0)
//result at this point: 3,874,923,
//remove the trailing comma
commaNumber = commaNumber.substring(0,commaNumber.length-1);
//add the decimal to the end
commaNumber += '.' + numArray[1];
//voila!
This function can be used for if not working locale somite
number =1000.234;
number=insertDecimalPoints(number.toFixed(3));
function insertDecimalPoints(s) {
console.log(s);
var temaparray = s.split(".");
s = temaparray[0];
var l = s.length;
var res = ""//+s[0];
console.log(res);
for (var i=0;i<l-1;i++)
{
if ((l-i)%3==0 && l>3)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res =res +"."+temaparray[1];
return res;
}
function convertDollar(number) {
var num =parseFloat(number);
var n = num.toFixed(2);
var q =Math.floor(num);
var z=parseFloat((num).toFixed(2)).toLocaleString();
var p=(parseFloat(n)-parseFloat(q)).toFixed(2).toString().replace("0.", ".");
return z+p;
}

Categories