Angularjs str_pad_left - javascript

Is there any angularjs or javascript function similiar to PHP str_pad_left ?
I could not get any result no input was written on screen.
Also i did not now if is it valid to pass the first parameter inside : {{}}.
I try use javascript str_pad function :
<script>
var num = str_pad({{ item.ID }}, 10,'','STR_PAD_LEFT')
document.write(num);
console.log('num '+num);
</script>
From this script :
function str_pad(input, pad_length, pad_string, pad_type) {
var half = '',
pad_to_go;
var str_pad_repeater = function(s, len) {
var collect = '',
i;
while (collect.length < len) {
collect += s;
}
collect = collect.substr(0, len);
return collect;
};
input += '';
pad_string = pad_string !== undefined ? pad_string : ' ';
if (pad_type !== 'STR_PAD_LEFT' && pad_type !== 'STR_PAD_RIGHT' && pad_type !== 'STR_PAD_BOTH') {
pad_type = 'STR_PAD_RIGHT';
}
if ((pad_to_go = pad_length - input.length) > 0) {
if (pad_type === 'STR_PAD_LEFT') {
input = str_pad_repeater(pad_string, pad_to_go) + input;
} else if (pad_type === 'STR_PAD_RIGHT') {
input = input + str_pad_repeater(pad_string, pad_to_go);
} else if (pad_type === 'STR_PAD_BOTH') {
half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
input = half + input + half;
input = input.substr(0, pad_length);
}
}
return input;
}

Related

How to get string converted to array?

I am kind of new to this, but this is giving me a headache.
Heres my code what i am trying to solve:
function parseComponents(data: any, excelAttributesArray: string[]) {
let confs = "";
let isValues = false;
let listValues = "";
if (!data) return confs;
if (data["Part"]) {
const part = data["Part"];
excelAttributesArray.forEach((attribute) => {
let attributeValue = part[attribute];
if (attributeValue !== null) isValues = true;
if (attributeValue !== null && attributeValue.Value) {
attributeValue = attributeValue.Value;
}
listValues += attributeValue + ",";
});
const number = part["Number"];
if (isValues) {
confs += `${listValues}${number}`;
}
}
if (data["Components"] && data["Components"].length > 0) {
for (let i = 0; i < data["Components"].length; i++) {
const tmp = parseComponents(
data["Components"][i],
excelAttributesArray
);
if (tmp && tmp.length > 0)
confs += (confs.length > 0 ? "|" : "") + tmp;
}
}
return confs;
}
The confs value is returned as a string. How do i get it return as array?

javascript function to add values outside of bracket into values inside the bracket

i am trying to create a function that automatically create questions to do.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var totalvar = getRandomInt(2,4);
var main = "";
for (var i = 1; i <= totalvar; i++) {
var test = getRandomInt(1,3);
// alert(test);
var myArray = ["A","B","C","A&apos;","B&apos;","C&apos;"];
var text ="";
for (var a = 1; a <= test; a++) {
function random(array) {
return array[Math.floor(Math.random() * array.length)]
}
var testing = random(myArray);
if (testing =="A") {
var testing2 ="A&apos;";
} else if (testing =="A&apos;") {
var testing2 ="A";
} else if (testing =="B") {
var testing2 ="B&apos;";
} else if (testing =="B&apos;") {
var testing2 ="B";
}else if (testing =="C") {
var testing2 ="C&apos;";
} else if (testing =="C&apos;") {
var testing2 ="C";
}
//alert(testing);
//alert(myArray);
text += testing
var index = myArray.indexOf(testing);
if (index > -1) {
myArray.splice(index, 1);
}
var index = myArray.indexOf(testing2);
if (index > -1) {
myArray.splice(index, 1);
}
}
var brackets = getRandomInt(1,3);
var chances = getRandomInt(1,3);
var lastLetter = main.charAt(main.length - 1);
if (brackets == 1) {
text = "(" + text + ")";
if (main == "") {
main = text;
} else if ( lastLetter == ')') {
if ( chances !== 1) {
main += text;
}else
main += "+" + text;
}else
main += "+" + text;
} else {
if (main == "") {
main = text;
} else if ( lastLetter == ')') {
if ( chances !== 1) {
main += text;
}else
main += "+" + text;
}else
main += "+" + text;
}
}
I have manage to get it to display questions that i want
B'C'+(A'C'B')+BCA
B+(C')(CAB)
A'BC+(C')A+AB'
B'C'+AB(A'C'B')+BCA
I am stucked as i couldnt get the function for the next step where it multiples the value outside the bracket
B'C'+A'C'B'+BCA
B+C'CAB
A'BC+C'A+AB'
B'C'+ABA'C'B'+BCA
The above is what i hope to achieve but im unable to create the function out
any tips guys?
use replace:
var str = "B'C'+(A'C'B')+BCA";
var response = str.replace(/([\(\)]+)/g, '');
console.log(response);
// output: "B'C'+A'C'B'+BCA"

convert a string containing boolean values to a boolean

If I have this ;
var a = "(true && false) && true && false"
And if I want to evaluate this string , what are the options ?
If I say, this code will be generated in the browser but there will be absolutely no user input in it , would it be safe to use eval ?
If not, what is the most performant way of parsing it ?
EDIt :
By the way, the string is dynamic , so I can't gaurantee that it's always like above , so it could be :
var a = "(true && false) || (true && (true && false)) && true && false"
FIY :
I know I can use eval, all I'm asking is, why I shouldn't use eval, or is there any other options?
EDIT : the original problem :
var a = function(){ return false} // all of them always return a boolean
var b = function(){ return true}
var c = function(){ return true}
var d = function(){ return false}
var conditions = "(a && b) && c && d"
I can't change the above code , I need to parse it, I need the condition to be evaluated ;
function ExecuteJavascriptString() {
var n = 0;
var s = "(true || false) || (true || (true || false)) && true";
var ifstate = " if (" + s + ") { console.log('done'); } ";
setTimeout(ifstate, 1);
}
ExecuteJavascriptString()
I was thinking maybe you can atleast verify that the string contains what you think it should contain, before running eval on it, using the RegExp /(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g:
var validExp = "(true && false && true) || (true && (true && false)) && true";
var evilExp = "(true && false && true) || (true && (true && false)) && true function() { console.log('do evil stuff'); }";
console.log(evalBoolStr(validExp)); //false
console.log(evalBoolStr(evilExp)); //Invalid input
function evalBoolStr(str) {
if(str.match(/(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g).join('') === str) {
return eval(str);
}
return 'Invalid input';
}
An attempt at actually writing a parser for boolean strings:
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
var exp1 = "(true && true || false) && (true || (false && true))";
var exp2 = "(true && false) && true && false";
var exp3 = "(true && !false) && true && !false";
var exp4 = "(a && b) && c && d";
console.log(exp1 + ' = ' + parseBoolStr(exp1));
console.log(exp2 + ' = ' + parseBoolStr(exp2));
console.log(exp3 + ' = ' + parseBoolStr(exp3));
console.log(exp4 + ' = ' + parseBoolStr(exp4));
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
function a() {
return false;
}
function b() {
return true;
}
function c() {
return true;
}
function d() {
return false;
}
Usage would then simply be parseBoolStr('true && false'); //false

Check and alert for the null value

I need to check for the null values and alert them if there are any before getting saved. I have used this code but I am not able to alert the null values instead it is getting saved . .
function fn_publish() {
var SessionNames = getParameterByName('SessionName');
var MenuType = getParameterByName('MenuType');
var Date = getParameterByName('ForDate');
var publish = "Y";
Dates = Date.split("-");
Date = Dates[1] + "/" + Dates[2] + "/" + Dates[0];
var rows = [];
cols = document.getElementById('product_table').rows[1].cells.length - 1;
table = document.getElementById('product_table');
for (var i = 1; i <= cols; i++) {
for (var j = 0, row; row = table.rows[j]; j++) {
if (j == 0) {
cust = row.cells[i].innerText;
alert(cust);
} else if (j == 1) {
catlg = row.cells[i].innerText;
alert(catlg);
} else {
if (typeof (row.cells[i]) != "undefined") {
if (row.cells[i].innerText != "") {
//alert(SessionNames+"::"+MenuType+"::"+Date+"::"+catlg+"::"+row.cells[0].innerText+"::"+row.cells[i].innerText+"::"+cust+"::"+publish);
fn_insert(SessionNames, MenuType, Date, catlg, row.cells[0].innerText, row.cells[i].innerText, cust, publish);
} else {
jAlert("Please select a product", "ok");
return false;
}
}
}
}
}
jAlert("Menu Published", "ok");
}
if (row.cells[i].innerText != "") {
May be the cells are containing empty space in that. Better trim ad then compare.
if (row.cells[i].innerText.trim() !== "") {
Also instead of innerText use textContent which is common in most modern browsers.
if (row.cells[i].textContent.trim() !== "") {

Any Good Number Picker for JQuery (or Javascript)?

Are there any good number picker for jquery (or standalone js)?
I would like a number picker where there is a max and min number that the user can choose from. Also, it have other options such as displaying odd number or even number or prime number or a range of number whereby some numbers in between are skipped.
Using a select to do this you can create an array with the numbers to skip and do a for loop to write the options:
int minNumber = 0;
int maxNumber = 10;
int[] skipThese = { 5, 7 };
for (int i = minNumber; i <= maxNumber; i++)
{
if(!skipThese.Contains(i)) Response.Write(String.Concat("<option value=\"", i, "\">", i, "</option>"));
}
You can do this with razor or any other way to output the HTML.
You can also do this with jQuery, dynamicaly, following the same idea:
$(document).ready(function() {
var minNumber = 0;
var maxNumber = 10;
var skipThese = [5, 7];
for (var i = minNumber; i <= maxNumber; i++) {
if ($.inArray(i, skipThese) == -1) $('#selectListID').append("<option value=\"" + i + "\">" + i + "</option>");
}
});
Edit:
Or you can use the C# code above in an aspx page and load it with AJAX from the page:
Create a select box in the page:
<select name="numPicker" id="numPicker">
<option>Loading...</option>
</select>
In a script in this page you could use jQuery's ajax() to fetch the data and populate the <select>:
$(document).ready(function() {
var numPickerSelect = $("#numPicker");
$.ajax({
url: 'url/to/page.aspx',
type: 'post'
success: function(data) {
numPickerSelect.find('option').remove(); // Remove the options in the select field
numPickerSelect.append(data); // Load the content generated by the server into the select field
},
error: function() {
alert('An error has ocurred!');
}
});
//Or use this (not sure if will work)
numPickerSelect.load("url/to/page.aspx");
});
I have used this. You should be able to modify to add extra options such as min and max fairly easily.
// Make a control only accept numeric input
// eg, $("#myedit").numeric()
// $("#myedit").numeric({alow: ' ,.'})
// $("#myedit").numeric({decimals: 2})
(function($) {
$.fn.alphanumeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
p = $.extend({
ichars: "!##$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",
nchars: "",
allow: "",
decimals: null
}, p);
return this.each
(
function() {
if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";
s = p.allow.split('');
for (i = 0; i < s.length; i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
p.allow = s.join('|');
var reg = new RegExp(p.allow, 'gi');
var ch = p.ichars + p.nchars;
ch = ch.replace(reg, '');
var dp = p.decimals;
var isInteger = function(val) {
var objRegExp = /(^-?\d\d*$)/;
return objRegExp.test(val);
};
var isNumeric = function(val) {
// If the last digit is a . then add a 0 before testing so if they type 25. it will be accepted
var lastChar = val.substring(val.length - 1);
if (lastChar == ".") val = val + "0";
var objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1," + dp + "})?|\\.\\d{1," + dp + "})\\s*$", "g");
if (dp == -1)
objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1,25})?|\\.\\d{1,25})\\s*$", "g");
var result = objRegExp.test(val);
return result;
};
$(this).blur(function(e) {
var text = $(this).val();
if (dp != null) {
if (dp == 0) {
if (!isInteger(text)) {
$(this).val('');
e.preventDefault();
}
}
else {
if (!isNumeric(text)) {
$(this).val('');
e.preventDefault();
}
}
} else {
var c = text.split('')
for (i = 0; i < text.length; i++) {
if (ch.indexOf(c[i]) != -1) {
$(this).val('');
e.preventDefault();
};
}
}
});
$(this).keypress
(
function(e) {
switch (e.which) {
//Firefox fix, for ignoring specific presses
case 8: // backspace key
return true;
case 46: // delete key
return true;
};
if (dp != null) {
if (e.which == 32) { e.preventDefault(); return false; }
var range = getRange(this);
var typed = String.fromCharCode(e.which);
var text = $(this).val().substr(0, range.start) + typed + $(this).val().substr(range.start);
if (dp == 0) {
if (!isInteger(text)) e.preventDefault();
}
else {
if (!isNumeric(text)) e.preventDefault();
}
return;
}
if (!e.charCode) k = String.fromCharCode(e.which);
else k = String.fromCharCode(e.charCode);
if (ch.indexOf(k) != -1) e.preventDefault();
if (e.ctrlKey && k == 'v') e.preventDefault();
}
);
$(this).bind('contextmenu', function() { return false });
}
);
};
$.fn.numeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
var opts = {};
if (!isNaN(p)) {
opts = $.extend({
nchars: az
}, { decimals: p });
} else {
opts = $.extend({
nchars: az
}, p);
}
return this.each(function() {
$(this).alphanumeric(opts);
}
);
};
$.fn.integer = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
p = {
nchars: az,
allow: '-',
decimals: 0
};
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
$.fn.alpha = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var nm = "1234567890";
p = $.extend({
nchars: nm
}, p);
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
})(jQuery);

Categories

Resources