Get the identifier [duplicate] - javascript

This question already has an answer here:
Set String via String.prototype function without return
(1 answer)
Closed 8 years ago.
At the starting I must tell that I am a newbie and sorry for a such a silly question
Second that .extract is just an example.
Here is the code
String.prototype.extract=function(start,end){
var value=this;
var rval="";
for(var i=start; i<=end; i++){
rval+=value.charAt(i)
}
????? = rval;
}
var str="abcdef";
str.extract(1,4)
alert(str) //must be bcde
Now I want the caller of method extract (str) and the value of rval must be saved to that only.
I could do it by:
str = str.extract;
and in the function return rval
but I want that like we do it as something.toUpperCase instead of something=something.toUpperCase
????? must be replaced by the caller of method extract (str)
any help would be useful

The best way to handle this is with a callback.
Re-using your code, it would look like:
String.prototype.extract=function(start,end, callback){
var value=this;
var rval="";
for(var i=start; i<=end; i++){
rval+=value.charAt(i)
}
callback(rval);
}
var str="abcdef";
str.extract(1,4, function(s1) {
alert(s1) //must be bcde
});
Another way to handle it would be to simply return the value and re-assign it to the original variable.
String.prototype.extract=function(start,end, callback){
var value=this;
var rval="";
for(var i=start; i<=end; i++){
rval+=value.charAt(i)
}
return rval;
}
var str="abcdef";
str = str.extract(1,4);
alert(str) //must be bcde

Related

RegExp exec not working in for loop snippet - Javascript [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 3 months ago.
Can someone help check this snippet? I'm just looping on array but the last item return false or null even its matches the pattern.
let texts = ["Invoice_001_1", "Invoice_001_2"];
var regTest = /(([a-zA-Z 0-9]+)_([0-9]+)_([0-9]+)$|[a-zA-Z ]+_([0-9]+)$)/gi;
for(var x=0; x<texts.length; x++) {
console.log(texts[x]);
var matchReg = regTest.exec(texts[x]);
console.log(matchReg);
}
JSfiddle Demo
The issue is that when using /g, js has a little gotcha, in that it tells the regexp to keep the index of the last match.The fix is to manually reset the index:
let texts = ["Invoice_001_1", "Invoice_001_2"];
var regTest = /(([a-zA-Z 0-9]+)_([0-9]+)_([0-9]+)$|[a-zA-Z ]+_([0-9]+)$)/gi;
for(var x=0; x<texts.length; x++) {
console.log(texts[x]);
var matchReg = regTest.exec(texts[x]);
console.log(matchReg);
regTest.lastIndex = 0;
}

Recursive function for clearing zeros in an array/string

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);

Javascript: Word reverse function undefined?

I am trying to create a word reverser function that will reverse the letter order of each word in a string, without using any loops.
So far I have this:
var strFlip = function(str){
splitStr = str.split(" ");{
return;
}
var wordFlip = function reverse(splitStr){
return splitStr.split('').reverse().join('');
};
};
console.log(strFlip("Hello Hannah"));
The wordFlip part correctly reverses the order of a single word if used independent of the rest of the code. However, the overall code continually outputs undefined. I am unfamiliar with Javascript, so I assume I am simply not noticing a simple structural issue.
Well, this part causes the function to return immediately, and since it is returning nothing, you get undefined:
var strFlip = function(str){
splitStr = str.split(" ");{
return; //<-- immediately returns here
}
...
};
I'm not sure what that part is trying to do, but to actually do what you want, you can do this:
var strFlip = function(str) {
//Since you are using a variable as a reference to a function
//expression/literal, there is no hoisting so you have to
//predefine
var wordFlip = function reverse(splitStr) {
return splitStr.split('').reverse().join('');
};
return str.split(" ").map(wordFlip).join(" ");
}
A more elegant approach would be to forgo wordFlip and just use an anonymous callback to map:
var strFlip = function(str) {
return str.split(" ").map(function(word) {
return word.split("").reverse().join("");
}).join(" ");
}
To understand what map does, let's look at forEach first since map works in a similar manner. When you use array.forEach(callback), the function callback is called for every element in array. It is equivalent to the following code:
var array = [1, 2, 3];
for(var i = 0; i < array.length; i++) {
callback(array[i]);
}
Essentially it is a "functional" way of iterating over an array and doing something with each element. map also does this; it iterates over the array as well, but converts (maps) each element of the array to something else and returns a new array consisting of the mapped elements. The something else is defined by the behavior of callback. Here's an example that is similar to the example above. Here I'm specifying an actual callback as well so that you can see the behavior a little better:
var array = [1, 2, 3];
var squares = [];
function square(num) {
return num * num;
}
for(var i = 0; i < array.length; i++) {
squares[i] = square(array[i]);
}
Here, square is the same as callback and it is called for each element. The return value of square is then used to construct the new array. Using map, you can rewrite the above as:
var squares = array.map(function(num) {
return num * num;
});
Now applying this to the solution, you can see that we are mapping each word in the sentence to its reverse and then joining on the mapped array.
You're overcomplicating things by trying to nest a function inside a function. Create a single function that does both the work of reversing the words and characters:
var flipper = function reverse(splitStr) {
return splitStr.split('').reverse().join('').split(' ').reverse().join(' ');
};
alert(flipper("Hello Hannah"));
You are pretty close, but the code is a little overbusy. Try this:
function reverse(splitStr) {
return splitStr.split('').reverse().join('');
}
console.log(reverse('Hello Hannah'));
I just took the main workhorse out of your code and simplified the function. You were on the right track,
EDIT
If you want to keep the words in place, like Vivin suggested, you can do something like:
function reverse(splitStr) {
var strs = splitStr.split(' ');
var reverseInPlace = [];
for (var i = 0; i < strs.length; i++) {
reverseInPlace.push(strs[i].split('').reverse().join(''));
}
return reverseInPlace.join(' ');
}
console.log(reverse('Hello Hannah'));
One approach would be split the sentence by empty spaces and then reverse and join empty spaces split again by a space then reverse and join with an empty space.
If you do that then:
"Hello Hannah" will be transformed to "olleH hannaH"
Edit: You can define the prototype to string as your own extension for one line solution.
String.prototype.Flip = function() {
return this.split("").reverse().join("").split(" ").reverse().join(" ");
};
var a="Hello Hannah";
alert(a.Flip());

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;
}

Add elements to 2D array in jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to create a two dimensional array in JavaScript?
I want to push elements to 2D array,
My code is,
var results = [];
var resultstemp = [];
function bindlinks(aamt,id1) {
resultstemp=results;
imagesArray.push($("#image1").mapster("get"));
if(results.length==0)
{
results.push([id1]);
}
else
{
var ck=0;
var lng=results.length;
for (var i = 0; i < lng; i++) {
if(results[i]==id1)
{
ck=1;
results = jQuery.grep(results, function(value) {
return value != id1;
});
}
}
if(ck==0)
{
results.push(id1);
}
}
I want to push id as well as aamt to array. Here i am pushing only id to array. I am not sure about how to add aamt to second position in 2D array.
Help me please,
Thank you
Change the declaration as follows:
var results = new Array();
and change the push as follows:
results.push([id1,aamt]);
Hope it would help
The logic behind the method to push two separate values in the same array evenly is something like this:
var array = [];
function push(id1, aamt) {
for (var i= 0; i < 10; i++) {
if (i%2 == 0) {
array.push(id1);
}
else {
array.push(aamt);
}
}
}
push(10, 12);
console.log(array); // 10, 12, 10, 12.....
Take note i abstracted the code quite a bit, because for me was not too obvious what the code should have to do, but the principle is simple: use the modulo (%) operator to test if the value is odd or even. If odd add the first value if even add the second value.
Hope it helps.

Categories