trim Array in JS - javascript

I Have an array say
['(','C','1','2',')']
Now I want to trim data from array beginning from indexOf('C') + 2 ,If it is a digit I need to remove it from array.. So for the above example final array has to be
['(','C','1',')']
For example if I have ['(','C','1','2','3','*',')'] I want it to be trimmed to ['(','C','1','*',')'] , After element 'C' only one numeral is allowed.
I know I can traverse the array by getting the indexOf('C') and then checking each element for numeric.. but help me with some efficient and better way. like using splice or something.

If the position from where you want to 'trim' is known, you could use filter here, like.:
var a = ['(','C','1','2','3','*',')']
.filter( function(a){
this.x += 1;
return this.x<=2 ? a : isNaN(+a);}, {x:-1}
);
Which could lead to this Array extension:
Array.prototype.trimNumbersFrom = function(n){
return this.filter( function(a){
this.x += 1;
return this.x<=n ? a : isNaN(+a);
}, {x:-1}
);
};
//=> usage
var a = ['(','C','1','2','3','*',')'].trimNumbersFrom(2);
//=> ["(", "C", "1", "*", ")"]
See also ...

var a = ['(','C', 'a', '8','2',')'].join("").split("C");
var nPos = a[1].search(/[0-9]/g);
var firstNumber = a[1][nPos];
var b = a[1].split(n);
// rebuild
a = a[0] + "C" + b[0] + firstNumber + b[1].replace(/[0-9]/g, "");
Not tested thoroughly but for your case it works.

You can use of isNaN() function which returns false if its a valid number or true if it's not a number
var str = ['(','C','1','2','3','4','*',')']; // Your Input
var temp = [],count = 0;
for(var i=0;i<str.length;i++)
{
if(i<str.indexOf('C') + 2)
{
temp[count] = str[i];
count++;
}
else
{
if(isNaN(str[i]) == true)
{
temp[count] = str[i];
count++;
}
}
}
str = temp;
alert(str);
LIVE DEMO

Related

How to insert default value in the comma separated strings?

I have group of comma separated strings and if any string is not a numeric value, I need to insert "(1)".
"stack(2),flow,over(4),temp(7)" Here insert default value to flow(1)
"stack(2),flow(3),over(4),temp" Here insert default value to temp(1)
"stack,flow(3),over,temp" Here insert default value to stack(1),over(1),temp(1)
I have validation code to validate and insert default values where needed. Please help me how to insert a default value within parentheses.
javascript function :
var case1 = "stack(2),flow(2),over(4),temp(7)"; // - true
var case2 = "stack(2),flow(3),over(4),temp(k)"; // - false
var case3 = "stack(2),flow(2),over(4),temp(0"; // - false
var case4 = "stack(2),flow(2),over(,temp)"; // - false
var case5 = "stack(2),flow(2),over(4)temp(8)"; // - false
var case6 = "stack(1),flow(7),over,temp"; // - true
var case7 = "stack(1),flow(7),OVER,Temp"; // - true
var case8 = "stack(1),flow(7),over_r,temp_t"; // - true
function testCases(str)
{
var pattern = /^[a-z]+(?:\(\d+\))?(?:,[a-z]+(?:\(\d+\))?)*$/
return pattern.test(str);
}
The above function works for validation in jsfiddle
tl;dr
Use String.prototype.split and String.prototype.join to process each part of your string.
Details
If you want to apply custom fixes to your string, you need to split it in several parts and then process them. Once the job is done, concat all the parts together.
Implementation
Using Array.prototype.map (Warning: not compatible with IE 8 and below):
Demo on JSFiddle.
function testCases(str) {
return str.split(',').map(function(s) {
if (s.match(/^[a-z]+\(\d+\)$/i)) {
// string is valid
return s;
} else {
// you can do processing here based on the failure reason
return s + '(1)';
}
}).join(',');
}
Using a for loop (IE8-compatible):
function testCases(str) {
var parts = str.split(',');
var i = parts.length;
while (i--) {
var s = parts[i];
if (!s.match(/^[a-z]+\(\d+\)$/i)) {
// string is invalid
// you can do processing here based on the failure reason.
parts[i] = s + '(1)';
}
}
return parts.join(',');
}
Unfortunately, JavaScript doesn't have lookbehinds - they'd be very useful here. Instead, we have to cheat:
str = str.replace(/([^)])(,|$)/g,"$1(1)$2");
What this does is capture whatever character comes before the comma or end of string, provided it is not a close-parenthesis. It then inserts the (1) default value in that position.
var add_default = function(str, def) {
str = str.split(',');
for(var i = 0; i < str.length; ++i) {
if(!/\(\d+\)$/.test(str[i]))
str[i] += "(" + def + ")";
}
return str.join(',');
};
http://jsfiddle.net/BhVx3/3/
Here is a possible solution :
function fix(input) {
var r = /^(.*?)(?:\((\d*)\)?|\)?)$/,
input = input.split(','),
output = [],
item;
while (item = input.shift()) {
item = item.match(r);
item = item[1] + '(' + (item[2] || 1) + ')';
output.push(item);
}
return output.join();
}
var s = 'stack(2),over(4),flow,hello(0,kitty2)';
s = fix(s); // "stack(2),over(4),flow(1),hello(0),kitty2(1)"

Javascript multiple digit index

I have searched around the net and the solution must be so simple no one has asked?
I just wanted to use an index like + i + to return 001, 002, 003, etc
How about
('000' + i).substr(-3);
So something like this?
function number_pad(num,len) {
num = ""+num;
while(num.length < len) num = "0"+num;
return num;
}
// Usage: number_pad(i,3);
Alternatively, extend the native object:
Number.prototype.pad(len) {
var num = ""+this;
while(num.length < len) num = "0"+num;
return num;
}
// Usage: i.pad(3);
For future reference, this is called zerofill or zero-padding.
function paddedNumber(n) {
// A string containing the fully padded zero value.
var zeroes = "000";
// The number as a string.
var numstr = "" + n;
var nDigits = numstr.length;
// Keep any sign at the front.
var sign = "";
if (/^[\+\-]/.test(numstr)) {
sign = numstr.charAt(0);
numstr = numstr.substring(1);
}
// Concatenates the number with just enough zeroes.
// No padding if itoa is already longer than the pad.
return sign + zeroes.substring(nDigits) + numstr;
}

JavaScript - Need help with string manipulation

say you have:
var foo = "donut [$25]"
What would you need to do in order to delete everything between and including the [ ].
so you get: foo = "donut" after the code is run.
So far I have tried most of the solutions below, but they all either do nothing or crash.
Maybe it's something with my code, please see below:
$('select').change(function () { OnSuccess(mydata); });
function OnSuccess(data) {
var total = 0;
$('select').each(function () {
var sov = parseInt($(this).find('option:selected').attr('value')) || 0; //Selected option value
var sop; //Selected Option Price
for (i = 0; i <= data.length; i++) {
if (data[i].partid == sov) {
sop = data[i].price;
total += sop;
$('#totalprice').html(total);
break;
}
};
//debugger;
$(this).find('option').each(function () {
// $(this).append('<span></span>');
var uov = parseInt($(this).attr('value')) || 0; //Unselected option value
var uop; //Unselected Option Price
for (d = 0; d <= data.length; d++) {
if (data[d].partid == uov) {
uop = data[d].price;
break;
}
}
//debugger;
var newtext = uop - sop;
//{ newtext = "" };
//if (newtext = 0) { newtext.toString; newtext = ""; };
//debugger;
var xtext = $(this).text().toString();
//if (xtext.match(/\[.*\]/) != null) {
xtext.replace(/\s*\[[\s\S]*?\]\s*/g, '').trim();
//}
// var temp = xtext.split('[')[0];
// var temp2 = xtext.split(']')[1];
// resultx = temp + temp2;
if (newtext != 0) {
//xtext.replace(/[.*?]/, "");
$(this).attr("text", xtext + " " + "[" + "$" + newtext + "]");
};
});
});
};
You can also use a regular expression, as Jon Martin pointed out:
var yum = "donut[$25]";
yum.replace(/[.*?]/, ""); // returns "donut"
Alternatively:
var temp = foo.split('[')[0];
var temp2 = foo.split(']')[1];
foo = temp + temp2;
You can use regular expressions (the RegExp() object) to match strings.
var foo = "donut[$25]";
foo.match(/\[.*\]/);
The above will return an array of every item in [square brackets], in this case ["[$25]"].
To just get one result as a string, specify the first index like so:
foo.match(/\[.*\]/)[0];
The above will return "[$25]"
Edit: You know what? I completely misread which bit of the string you're after. This is what you're after:
var foo = "donut[$25]";
foo.match(/\w*/)[0];
How about simply;
var yum = "donut[$25]";
print( yum.substr(0, yum.indexOf("[")) );
>>donut
var begin = foo.search("[");
var end = foo.search("]");
var result = foo.substr(0, begin) + foo.substr(end+1); //Combine anything before [ and after ]
Should be ok right?
Your question leaves unspecified the treatment of the spaces before the [ character, anything after the ], will your string ever contain a linefeed character, multiple occurrences of [..], leading or trailing spaces.
The following will replace all occurrences of 'spaces [ ... ] spaces' with a single space, then it trims the result to remove any leading/trailing spaces.
v.replace (/\s*\[[\s\S]*?\]\s*/g, ' ').trim ();

Append number to a comma separated list

the list looks like:
3434,346,1,6,46
How can I append a number to it with javascript, but only if it doesn't already exist in it?
Assuming your initial value is a string (you didn't say).
var listOfNumbers = '3434,346,1,6,46', add = 34332;
var numbers = listOfNumbers.split(',');
if(numbers.indexOf(add)!=-1) {
numbers.push(add);
}
listOfNumbers = numbers.join(',');
Basically i convert the string into an array, check the existence of the value using indexOf(), adding only if it doesn't exist.
I then convert the value back to a string using join.
If that is a string, you can use the .split() and .join() functions, as well as .push():
var data = '3434,346,1,6,46';
var arr = data.split(',');
var add = newInt;
arr.push(newInt);
data = arr.join(',');
If that is already an array, you can just use .push():
var data = [3434,346,1,6,46];
var add = newInt;
data.push(add);
UPDATE: Didn't read the last line to check for duplicates, the best approach I can think of is a loop:
var data = [3434,346,1,6,46];
var add = newInt;
var exists = false;
for (var i = 0; i < input.length; i++) {
if (data[i] == add) {
exists = true;
break;
}
}
if (!exists) {
data.push(add);
// then you would join if you wanted a string
}
You can also use a regular expression:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
if (!re.test(s)) {
return s + (s.length? ',' : '') + n;
}
return s;
}
var nums = '3434,346,1,6,46'
alert( appendConditional(nums, '12') ); // '3434,346,1,6,46,12'
alert( appendConditional(nums, '6') ); // '3434,346,1,6,46'
Oh, since some really like ternary operators and obfustically short code:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
return s + (re.test(s)? '' : (''+s? ',':'') + n );
}
No jQuery, "shims" or cross-browser issues. :-)

How to make 8 digit number in javascript?

I am trying to make an auto-generator of numbers. but I'm having a problem on how to forced the number to 8 digit.
for(i=1;i<=100;i++) {
var i = x++;
var test = i.toFixed(8); // I used this but this is only for decimals
jQuery('.generated_table').append(test+'<br />');;
}
Please help.
Use toPrecision:
(10000000).toPrecision(8); //=> '10000000'
(100).toPrecision(8); //=> '100.00000'
If you meant preceding a number with leading zero's:
var i = (100).toPrecision(8).split('.').reverse().join(''); //=> '00000100'
You can also make a Number.prototype function of that:
Number.prototype.leadingZeros = function(n) {
return this.toPrecision(n).split('.').reverse().join('');
};
(100).leadinZeros(8); //=> '00000100'
Just to be complete: a more precise way to print any (number of) leading character(s) to any number may be:
Number.prototype.toWidth = function(n,chr) {
chr = chr || ' ';
var len = String(parseFloat(this)).length;
function multiply(str,nn){
var s = str;
while (--nn>0){
str+=s;
}
return str;
}
n = n<len ? 0 : Math.abs(len-n);
return (n>1 && n ? multiply(chr,n) : n<1 ? '' : chr)+this;
};
(100).toWidth(8,'0'); //=> 00000100
Whooo!!! i got anser :: Try it
for(i=1;i<=100;i++) {
//var i = x++;
var test = i.toPrecision(8).replace("\.","");
jQuery('.generated_table').append(test+'<br />');;
}
Check out this SO question for some links to various printf-style functions for Javascript: Javascript printf/string.format
var randNum = "";
var MAX_LENGTH = 8;
while(randNum.toString().length < MAX_LENGTH){
var temp = Math.floor(Math.random() * 10);
randNum += temp.toString();
}
alert(randNum);

Categories

Resources