I have a function with the name MakeInitialCapital. I want to supply control name as an argument and the text in that control must be converted to Initial Capital.
How to modify this Javascript code:
function MakeInitialCapitalControl(controlName)
{
TextInControl = getElementByID(controlName).value;
return str.toLowerCase().replace(/\b[a-z]/g, cnvrt);
function cnvrt() {
return arguments[0].toUpperCase();
}
Edited:
One more thing, if the text already has Intials Capital, make it lowercase.
Assuming the rest of your code works, you need to assign the value, rather than returning it:
function MakeInitialCapitalControl(controlName)
{
var ctrl = getElementByID(controlName);
ctrl.value = ctrl.value.toLowerCase().replace(/\b[a-z]/g, function {
return arguments[0].toUpperCase();
});
}
EDIT
As for the request in your edit... that's a rather strange request. Are you sure you want that in the same function? It'll do pretty much the exact opposite of what the function name implies. But oh well:
function MakeInitialCapitalControl(controlName)
{
var ctrl = getElementByID(controlName);
if(/^[A-Z]/.test(ctrl.value)) {
ctrl.value = ctrl.value.toLowerCase();
return;
}
ctrl.value = ctrl.value.toLowerCase().replace(/\b[a-z]/g, function {
return arguments[0].toUpperCase();
});
}
Related
So I have the following problem at hand;
I want to getText from a registrationNumber. so I defined a var regNumber = null;
I defined the var in global.js because I want to access the var throughout the whole test with different pageObjects and outside of a specific function.
When it gets the text and it needs to fill in the text with setValue in the Template Search it returns Object Object, so I tried to use toString but is the same.
this is the function which I need to use in order to use the var
module.exports = {
var regNumber = browser.globals;
Page Object
openSearch: function(browser, regNumber ) {
browser.perform(function () {
browser.waitForElementVisible('.registrationnumber-search input', 3000)
browser.setValue('.registrationnumber-search input', regNumber )
return this;
})
Test
.continueButton()
browser.getText('xpath', '//*[#id="wizardDetailsTab"]/div[1]/div/div[1]/h4/span[2]', function (result) {
regNumber = result.value
console.log(result.value)
})
certificateEditor
.quickMenu("Permit")
.createNewItem("template")
permit
.openSearch(browser, regNumber)
The console.log(result.value) returns the value which I want, however it does not work when I want to use that value in setValue. If I create a function and do the getText in that scope, it fills in what I need. BUt I want to know why it does not work when I try it like this.
Thanks in advance!
in your page object :
openSearch: function(regNumber ) {
return this.perform(function (done) {
this.api.waitForElementVisible('.registrationnumber-search input', 3000)
.setValue('.registrationnumber-search input', regNumber )
done(); //prevent timeout issue
})
Move the code after getText() into it.
var permit=client.page.permit() // replace .permit() as .yourpageobjectjsname()
.....
.continueButton()
browser.getText('xpath', '//*[#id="wizardDetailsTab"]/div[1]/div/div[1]/h4/span[2]', function (result) {
regNumber = result.value
console.log(result.value)
certificateEditor
.quickMenu("Permit")
.createNewItem("template")
permit
.openSearch(regNumber)
})
From the looks of it what's happening is you're returning an Object, when you're looking for a string. I think you just need to designate the object you want.
browser.globals
should be something like
browser.globals.value or browser.globals.text
Your browser.globals is the object being returned. You have to specify what key/value pair you want that object to return.
To help understand this the function is in the html page and it is generated, I cannot change the generated code:
function Update_qu7260() {
var newVal = ''
for( var idx = 0; idx < 2; idx++ )
{
var test
if( idx == 0 ) test = text7263
else if( idx == 1 ) test = text7265
if( test.matchObj ) newVal += test.leftSel + "-" + test.matchObj.rightSel + ","
}
newVal = newVal.substring( 0, newVal.length-1 )
VarQuestion_0001.set( newVal )
qu7260.hasBeenProcessed=false;
doImmFeedback('qu7260');
}
var qu7260 = new Object();
...
qu7260.updFunc = Update_qu7260;
var qObj=[qu7260];
Note in the above the number "7260", the numbers start at 1 so there are lots of them and each Update_###() will be different so I cannot re-write them with "hard wired" code. My code is in an external JavaScript file and is executed onLoad:
...
var updFunc = qObj[0].updFunc.toString();
if(updFunc.indexOf('doImmFeedback(')!=-1){
updFunc = updFunc.replace('doImmFeedback','doImmQuestionFeedback'); // do my function
updFunc = updFunc.replace('function ',''); // remove the word function
var funcName = updFunc.substr(0,updFunc.indexOf('(')); // get the function name e.g. Update_qu7260
updFunc = "window['" + funcName + "']=function" + updFunc.replace(funcName,'');
eval(updFunc);
}
...
When I change the eval() to alert() I can see the that it's correct, however, the eval() is not raising any errors and my function doImmQuestionFeedback is not being called. When I subsequently do an alert(qObj[0].updFunc.toString()) I see the original function.
It would seem that I have provided information that is too complex, so the following code is a better example:
function hi(){alert('hi');}
function changeHi(){
hi(); // I get an alert box with hi
newHi = "function hi(){alert('hi there');}"
eval(newHi);
hi(); // I get an alert box with hi
window.setTimeout('hi()',500); // I get an alert box with hi
}
window.setTimeout('changeHi()',500);
The following is the original question:
I have a predefined function that I did not create, however, I know it's name so I can get the function itself and then I change it by doing:
var funcText = window.updateFunc.toString();
funcText = funcText.replace('doSomeOtherFunction(','doMyFunction(');
How do I update the actual function so it will do all that it did before except it will now call doMyFuntion()?
The following is an example to help visualize what I want to do, the actual function I need to change is very complex. I have:
function updateFunc(whatToUpdate,true){
... - do lots of stuff.
var retVal = doSomeOtherFunction(whatToUdate);
... - do lots of stuff based on retVal
}
I need to change this to:
function updateFunc(whatToUpdate,true){
... - do lots of stuff
var retVal = doMyFunction(whatToUdate);
... - do lots of stuff based on retVal, I have had a chance to change retVal
}
Then the first thing my function will do is call doSomeOtherFunction() check/change the returned value and subsequently return the value to the updateFunc().
I have tried to manipulate the funcText above to:
funcText = 'window.updateFunc = function(...';
eval(funcText);
Without success.
This may be closed enough to what you are looking for.
Assuming you have this original function:
function originalFunc(val) {
// this function converts input string to upper case
return val.toUpperCase();
}
Now you want to override it to something either before or after you execute that function (in this example, we execute before, of course before or after doesn't matter in this case).
// we preserve orignal function
var originalFunc_save = originalFunc;
// now we override the original function with this block
var originalFunc = function(text) {
// lets call the orignal function
text = originalFunc_save(text);
// now do our custom thing
return text.split('').reverse().join('');
}
So our test should work.
var text = 'This is a test';
console.log(originalFunc(text));
Output:
TSET A SI SIHT
This method also works if you have to override functions inside a class. The only thing we have to be careful of is to choose a saved name that doesn't interfere with the original class code. _save may not be good enough, but you get the idea.
UPDATE: I'm updating this code above to use a string variable pointing to the original function. I think this is what the OP wanted.
Original code which defined by some library
function originalFunc(val) {
// this function converts input string to upper case
return val.toUpperCase();
}
Now we use the func string variable to point to that function and execute it.
var text = 'This is a test';
var func = 'originalFunc';
text = window[func](text);
console.log(text);
Output: Of course we get the original intended result because we haven't overridden it.
THIS IS A TEST
Now we write our code to override the original function behavior using a string pointing to the function.
// let's define a new function string
var funcSaved = func + '___saved';
// now preserve the original function code
window[funcSaved] = window[func];
// override the original function code block
window[func] = function(text) {
// lets call the orignal function
text = window[funcSaved](text);
// now do our custom thing
return text.split('').reverse().join('');
}
// let's test the code
text = 'This is a test';
text = window[func](text);
console.log(text);
Output:
TSET A SI SIHT
You can make a clone of updateFunc function, edit it at your discretion and work with it in what follows.
function updateFunc(whatToUpdate, param){ // the initial function
...
var retVal = doSomeOtherFunction(whatToUpdate);
return retVal;
}
// formation of unnamed function as string
var newfunc = updateFunc.toString().replace('function updateFunc', 'function ').replace('doSomeOtherFunction(', 'doMyFunction(');
function doMyFunction(whatToUpdate){ // your new function, just for example
console.log(parseInt(whatToUpdate) * 10);
}
var newUpdateFunc;
// declaring new version of 'updateFunc' function
// which is stored in 'newUpdateFunc' variable
eval("newUpdateFunc = " + newfunc);
newUpdateFunc(3); // outputs '30'
I believe this is a valid use case for the forgotten JavaScript with feature.
Basic idea: you call original updateFunc supplying your own version of doSomeOtherFunction to it using with namespace injection:
function updateFunc(whatToUpdate,true){
... - do lots of stuff.
var retVal = doSomeOtherFunction(whatToUdate);
... - do lots of stuff based on retVal
}
function patchUpdateFunc() {
var original_doSomeOtherFunction = window.doSomeOtherFunction;
var original_updateFunc = window.updateFunc;
function doMyFunction() {
// call original_doSomeOtherFunction() here,
// do your own stuff here.
};
window.updateFunc = function() {
with ({doSomeOtherFunction: doMyFunction}) {
return original_updateFunc.apply(this, arguments);
}
}
}
patchUpdateFunc();
I think you are going at this way too complicated.
If you only have doMyFunction and doSomeOtherFunction to switch between, you could just create a flag somewhere telling you to use one or the other when used in an if-statement.
If you want to call a function with a name you do not know beforehand and you only get a name during runtime, you could either accept the function to call as a parameter or accept the name of the function as a parameter and call it like so: var retVal = window[functionName](); (assuming functionName is a property of the window object).
I would highly recommend directly accepting a function as a parameter since the function may not be defined in a global scope.
EDIT:
After your clarification, I think, I can give you a satisfying answer:
if you have a string like var functionString = "function updateFunc(whatToUpdate){var retVal = doMyFunction(whatToUpdate);}";
You can define a function using a Function object:
window.updateFunc = new Function("whatToUpdate", "return (" + functionString + ")(whatToUpdate)");
This will replace the already existing function and you can give it any valid function string you want as long as you know and specify the arguments.
If I understood correctly, you want to override the external function. You can achieve that with the following code
//Someone else's function
function externalFunction(foo){
return "some text";
}
//Your function
function myFunction(value){
//Do something
}
//Override
var externalFunction = (function(){
var original = externalFunction; //Save original function
return function(){
var externalFunctionReturnValue = original.apply(this, arguments);
return myFunction(externalFunctionReturnValue);
}
})();
I strongly sugest not to use eval, but since you want to parse javascript from string:
function hi(){alert('hi');}
function changedHi(){
hi(); // I get an alert box with hi
newHi = "window['hi'] = function(){alert('hi there');}"
eval(newHi);
hi(); // I get an alert box with hi there
window.setTimeout('hi()',500); // I get an alert box with hi there
}
window.setTimeout('changedHi()',500);
UPDATE:
This code snippet works which is your original code:
<script type="text/javascript">
function doImmFeedback(foo){
console.log("DoImmFeedback: " + foo);
}
function Update_qu7260() {
console.log("Some code")
doImmFeedback('qu7260');
}
</script>
<script type="text/javascript">
var qu7260 = new Object();
qu7260.updFunc = Update_qu7260;
var qObj=[qu7260];
var updFunc = qObj[0].updFunc.toString();
if(updFunc.indexOf('doImmFeedback(')!=-1){
updFunc = updFunc.replace('doImmFeedback','doImmQuestionFeedback'); // do my function
updFunc = updFunc.replace('function ',''); // remove the word function
var funcName = updFunc.substr(0,updFunc.indexOf('(')); // get the function name e.g. Update_qu7260
updFunc = "window['" + funcName + "']=function" + updFunc.replace(funcName,'');
console.log(updFunc);
eval(updFunc);
}
function doImmQuestionFeedback(foo){
//Your function
console.log("doImmQuestionFeedback: " + foo);
}
Update_qu7260(); //This executes your doImmQuestionFeedback
</script>
So if your function isn't running, your function isn't in the global scope, or something else is happening, and we can't know if don't have any more info. Check your developer's console for javascript errors.
I have a javascript that I am using to pull id of a tag . But due to some limitation on a platform where I need to use this I have to make this script under function so I will get the output in return. I am trying but I am failing to get it.
This is the script I have;
var arr2st3 = [].map.call(document.querySelectorAll('article:nth-child(-n+4)'), function(el) {
return el.id.replace(/[^\d]/g, '');
});
This is what I am trying to come up;
function myfun() {
var arr2st3 = []
var arr2st3 = arr2st3.map.call(document.querySelectorAll('article:nth-child(-n+4)'),
function(el) {
return el.id.replace(/[^\d]/g, '');
});
return;
console.log(myfun);
}
This is the test url -> https://jsfiddle.net/v3d0nz9d/
I need to get output in return as ['123456', '7896669', '1147777']
Any help would be highly appreciated.
TIA
[].map is shorthand for Array.prototype.map, so you don't need to store that in a variable, you can just return the return value of your map. Anything after a return statement won't be called, so your console.log is never reached. Also, to log the values returned from your function, you need to call it in your console.log.
function myfun() {
return [].map.call(document.querySelectorAll('article:nth-child(-n+4)'), function(el) {
return el.id.replace(/[^\d]/g, '');
});
}
console.log(myfun());
Say I have a function name myFunA, when the first time call the function and pass a parameter to it, the function actually stored the variable. Each time I call this function, it will return the same variable, until I call the function again and pass a parameter to replace the previous parameter.
function myFunA(input){
if(input exist){
storedVar = input //declare a variable and store the input
}
console.log(storedVar);
}
myFunA('First Input'); // output will be 'First Input'.
myFunA(); // output will still be 'First Input'.
myFunA('Second Input'); // output will be 'Second Input'.
myFunA(); // As the variable is replaced, the output will still be 'Second Input'.
Is this possible?
I know that there is a Garbage Collection feature in JavaScript to scrap the variable and release memory, but is there anyway to prevent?
Really appreciate if someone could let me know the way. If this is not possible to achieve, it is still good to confirm it.
Thank you so much.
Javascript functions are first class objects. Therefore, you can set a property of the function just like any other variable.
function myFunA(input) {
if (input) {
myFunA.storedVar = input;
}
console.log(myFunA.storedVar);
}
myFunA('First Input'); // First Input
myFunA(); // First Input
myFunA('Second Input'); // Second Input
myFunA(); // Second Input
The answer of #NinaScholz is fine, but allows you to change the stored value without calling the function. If you want to avoid it, here is another pattern :
var myFunA = (function() {
var storedVar = null;
return function(input) {
if(typeof(input) != "undefined") {
storedVar = input;
}
console.log(storedVar);
};
})();
I want to pass one parameter to a function called ForPaste().
My function is given below:
var regex = /^[A-Za-z0-9ĀĒĪŌŪāēīōū\.\-\~\`\'' ]*$/;
var SalaryRegex = /^[A-Za-z0-9\,\.\/\$ ]*$/;
$.fn.ForPaste = function () {
return this.each(function () {
$(this).bind('input propertychange', function () {
var value = $(this).val();
if (!regex.test(value)) {
$(this).val("");
}
});
});
};
This function is in a common JS file. It is called on individual pages. I want to test the regex depending on the parameter passed. So can I know the method about to call the ForPaste() function with the parameter.e.g $("#Text1").Forpaste('FromForm1'); and I get this FromForm1 in the ForPaste() function.
You define a formal parameter for your function.
// formal parameter--v
$.fn.ForPaste = function (the_value) {
alert( the_value ); // displays the argument passed
// rest of your code
};
Whatever value was passed to ForPaste() will be referenced by the_value. (Of course you can change the name to any valid identifier.)
not sure what you are trying to do, because the answer seems so obvious. Will this do?
$.fn.ForPaste = function (theName) {
if (theName.test(//)){
return this.each(function () {
....
});
}
return false
};
you can access the parameters by looking at arguments which isn't an array, but seems to be one. from within the function you can do an var theName=arguments[0] to get the value of the first parameter