Recursive function for clearing zeros in an array/string - javascript

I need a function where I can clear off the zeros which appears at the beginning of my string, basically something like '0000213' in javascript. I just want the '213' and not the zeros. Here is the code that I have written but theres some problem with the array length in the for loop, can someone please help me with this. https://jsfiddle.net/066by2cv/3/

Try this solution.
'0000213'.replace(/0+/,'');
or
Number('0000213').toString();
or just
+'0000213' + ''

Although already answered by #Tresdin, in case you really want your function, you can use
var str = '0003';
function Iterate(val) {
var start = 0;
for (var i = 0; i < val.length; i++) {
if (val.charAt(i) == '0') {
start = i;
}
}
return val.substr(start+1);
}
var re = Iterate(str);
alert(re);

Related

Best way to re-format JS code snipet

I wanted to reformat below code in order to keep as minimum as possible Any suggestion to re-format below code and use it as one single method.
function Cookie_Exist(cookieName) {
var all_cookies = document.cookie.split(';');
for (i = 0; i < all_cookies.length; i++) {
var temp_cookie = all_cookies[i].split('=');
var cookie_name = temp_cookie[0].replace(/^\s+|\s+$/g, '');
if (cookie_name === cookieName) {
return true;
}
}
return false;
}
function Get_Cookie(cookieName) {
var all_cookies = document.cookie.split(';');
for (i = 0; i < all_cookies.length; i++) {
var temp_cookie = all_cookies[i].split('=');
var cookie_name = temp_cookie[0].replace(/^\s+|\s+$/g, '');
if (cookie_name === cookieName) {
return temp_cookie[1];
}
}
return null;
}
Instead of reparsing the cookies everytime one could do that once and build up a Map:
const cookies = new Map(document.cookie.split(";").map(pair => pair.split("=")));
Then its as simple as
cookies.get("name");
or
cookies.has("name")
If you had to keep the function Cookie_Exist rather than #Jonas's method, you would do well to use the array methods rather than a for loop. The abstraction can make code shorter and clearer:
function Cookie_Exist(cookieName) {
const allCookies = document.cookie.split(';');
return allCookies.includes(cookieStr => {
const thisCookieName = cookieStr.split('=')[0].replace(/^\s+|\s+$/g, '');
return cookieName === thisCookieName;
});
}
You don't need the Cookie_Exist() function at all, it does the same as the Get_Cookie() function. Use the Get_Cookie() everywhere instead of Cookie_Exist() and check your result. If it is false, then the cookie does not exist. As simple as that.
You may want to clarify what you mean by 'as minimum as possible.' If you're referring to being efficient, you definitely should go the route suggested by Jonas W.
If you're referring to reducing line count? His answer also is a good one, but I would recommend not focusing too much on line counts. Readability should be your number one goal. In other words, what you should be trying to keep to a minimum is the number of mental hoops a human reader of your code must jump through to understand what is going on.
Also, the regex you're doing to strip whitespace can be replaced with String.prototype.trim() which exists for this purpose.
function parseCookie(cookie) {
let { name, value } = cookie.split('=');
return [ name.trim(), value ];
}
function parseCookies() {
let cookies = document.cookie.split(';')
return new Map(cookies.map(parseCookie))
}
// Usage:
const cookieMap = parseCookies();
cookieMap.has('name');
cookieMap.get('name'):

FreeCodeCamp: checking for palindromes

This is my first question, so I apologize if this isn't formatted correctly or placed in the proper area.
I just completed the FreeCodeCamp checking for palindromes challenge. I can't help but think my solution was very inelegant.
function palindrome(str) {
var cleanString = str.replace(/[^A-Za-z0-9]/g, '');
var lowerCleanString = cleanString.toLowerCase();
var lowerArr = lowerCleanString.split('');
var reverseArr = lowerArr.reverse();
var joinedArr = reverseArr.join('');
if (joinedArr === lowerCleanString) {
return true;
}
// Good luck!
else {
return false;
}
}
I know it worked, but is it possible to do some of these steps together or in a cleaner way?
Simple function to check for palindromes
function checkPalindrome(palindrome) {
return palindrome == palindrome.split('').reverse().join('');
}
function palindrome(str) {
var newstr = str.replace(/[\W_]/g,'').toLowerCase();
if(newstr === newstr.split('').reverse().join('')){
return true;
}
return false;
}
palindrome("five|\_/|four");
You can use many methods in one row like I've used them .It's more simple :)
Good luck
Wow, I really like the answers comparing the string to a string.split('').reverse().join('') version of itself. I didn't think about that. Forgot about the .reverse() function. I ended up processing the string and splitting it out into an array and then using a double counter for the loop to compare the first and last items in the array. Was kinda fun to learn how to do that, but I like the .reverse() function use better.
In case someone is curious about the for loop I used ...
for(let i = 0, j = arr.length-1; i < j; i++, j--) {
if (arr[i] !== arr[j]) {
return false;
}
}

Creating a new function that takes default arguments for another function (Javascript)

I am currently trying to create a defaultArguments function that takes in a function and some parameters that are set as default values. The steps I am thinking about taking to solve this particular problem is to:
Parse through the function in order to obtain what its arguments which could be anything.
Go through each argument that was extracted and replace arguments that have input parameters to its respective value.
Now, what I was thinking about doing next was to add additional default arguments into the input 'func'. I tried to:
Look up how to input a string as an argument into an existing function. However, the function then just reads the argument string as just a string.
Use the JavaScript .apply method. However, I won't always have all input values.
Here is the code I wrote so far.
function defaultArguments(func, params) {
var reg = /\(([\s\S]*?)\)/;
var extractVar = reg.exec(func);
if (extractVar) {
var arguments = extractVar[1].split(',');
}
for (i = 0; i < arguments.length; i++) {
if (params[arguments[i]]) {
arguments[i] = params[arguments[i]];
}
}
}
So for example, if I have a function
function add(a,b) { return a+b; };
I would use the defaultArguments function as such
var add_ = defaultArguments(add,{b:9});
console.log(add_(10) === 19); // b is defaulted to 9
console.log(add_(10,7) === 17); // b is given so use given value
console.log(add_()); // NaN
I would love some hints as to how to solve this problem and a different approach if I am approaching this problem incorrectly. I appreciate your time for reading this and I hope to see your response!
UPDATE:
So I was able to come up with a rough solution for this question. I was wondering if I approached the problem correctly and if there's any improvements do to my code. After researching a lot, I know that I shouldn't use eval(), but I don't know how else to tackle the problem. I am open to suggestions. Thanks in advance!
function defaultArguments(func, params) {
var stringed = func.toString();
var inputs = stringed.match(/\(.+\)/)[0].replace("(", "").replace(")", "").split(",")
for (i = 0; i < inputs.length; i++) {
inputs[i] = ""+inputs[i]+" = "+inputs[i]+" || "+params[inputs[i]]+";"
}
for (i = 0; i < inputs.length; i ++) {
stringed = stringed.replace("{", "{ "+inputs[i]+"")
}
var newFunc = "var restoreFunc = " + stringed;
eval(newFunc);
return restoreFunc;
}

Loop through array checking for indexOf's more simple?

Okay, like the title says. I have a array looking like this:
var hiTriggers = new Array();
hiTriggers = ["hi", "hai", "hello"];
And I'd like to check through it if it finds either of those. I can already achieve this by doing the following:
if(message.indexOf("hi") >= 0) {
// do whatever here!
}
But I'm looking for an more efficient way rather than doing 100 if() checks. Such as loop through an array with the "hiTriggers".
I tried the following:
for(var i; i < hiTriggers.length; i++) {
console.log(hiTriggers[i]); // simply to know if it checked them through)
if(message.indexOf(hiTriggers[i]) >= 0) {
//do stuff here
}
}
Which sadly did not work as I wanted as it does not check at all.
Thanks in advance and I hope I made sense with my post!
Edit; please note that I have 'messaged' already 'declared' at another place.
It doesn't run because you didn't give the i variable an initial value. It is undefined.
Change to use var i=0;:
for(var i=0; i < hiTriggers.length; i++) {
//console.log(hiTriggers[i]); // simply to know if it checked them through)
if(message.indexOf(hiTriggers[i]) >= 0) {
//do stuff here
console.log("found " + hiTriggers[i]);
}
}
Try using a regular expression to match the message. The \b is a word boundary marker, and the words between the | characters are what is being searched for. If any of the words appear in the message, then message.match will return the array of matches, otherwise null.
var pattern = /\b(Hello|Hi|Hiya)\b/i;
var message = "Hello World";
if (message.match(pattern))
{
console.log("do stuff");
}
You can write even simpler using a for in loop:
for(var v in hiTriggers){
if(message.indexOf(hiTriggers[v]) >= 0) {
//do stuff here
console.log("found " + hiTriggers[v]);
}
}
Problem is becoz - you have not initialized your var i, make it var i = 0;
You can try forEach loop.
hiTriggers.forEach(function(e) {
if(message.indexOf(e) >= 0) {
//do sthg here
}
})

JQuery for loop

I need to Loop in JQuery from 0 to variable-value(dynamically entered by user).How can i achieve this?
Now i am doing it by using simple For loop like this.
for( i=1; i<=fetch; i++) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Thanks.
You could loop an empty array:
$.each(new Array(fetch), function(i) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
});
If you do this alot you can even fake-patch jQuery.each to take numbers:
(function($) {
var _each = $.each;
$.each = function() {
var args = $.makeArray(arguments);
if ( args.length == 2 && typeof args[0] == 'number') {
return _each.call(this, new Array(args[0]), args[1]);
}
return _each.call(this, args);
};
}(jQuery));​
$.each(fetch, function(i) {
// loop
});
jQuery.each does have some great features, like the different return values inside the callback. But for a simple loop I find it much more convenient (and less overhead) to do something like:
while(fetch--) {
// loop
}​
To loop between two values you should use a regular Javascript loop. The jQuery each methods are used when looping through a collection of elements or an array.
To loop from zero, you should initialise the loop variable to zero, not one. To loop from zero to the specified value, you use the <= for the comparison, but to loop from zero and the number of items as specified (i.e. from 0 to value-1), you use the < operator.
for (i = 0; i < fetch; i++) {
$('body').append($('<input/>', { type: 'text' }));
}
You mean Javascript loop.
From W3Schools:
for (var variable = startvalue; variable < endvalue; variable = variable + increment)
{
//code to be executed
}
To get the value from user and run the code you can use the following prompt.
var x=prompt("Enter the value",0);
for(i=0;i<x;i++)
{
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Hope this helps.
Thanks
If you want it the full jQuery way then use that new plugin jQuery-timing. It provides inline-loops in your jQuery line:
$('body').repeat().append('<input>').until(fetch);
Nice, eh?

Categories