Replace function showing undefined in the console [duplicate] - javascript

This question already has answers here:
JS replace not working on string [duplicate]
(2 answers)
Closed 7 months ago.
So, I was trying to create e encryption app, the app should take the value of the input and use the replace function to change the letters to the words that I specified in the function trocaLetras, but it just returns undefined in the console log.
This is my code:
var botaoCriptografar = document.querySelector('#criptografar');
function trocaLetras(conteudoInput) {
conteudoInput.replace(/a/g, 'ai');
conteudoInput.replace(/e/g, 'enter');
conteudoInput.replace(/i/g, 'imes');
conteudoInput.replace(/o/g, 'ober');
conteudoInput.replace(/u/g, 'ufat');
}
botaoCriptografar.addEventListener('click', function(event){
event.preventDefault();
var texto = document.querySelector('#texto-para-coleta').value;
var textoAtualizado = trocaLetras(texto);
console.log(textoAtualizado);
});
<textarea id="texto-para-coleta"></textarea>
<button id="criptografar">Criptografar</button>

The replace function will actually not change the value in the variable, but instead returns a string with the replaced characters. So you must chain multiple calls of replace.
Also your function needs to return the result. So your function works if you change it to this:
function trocaLetras(conteudoInput) {
return conteudoInput.replace(/a/g, 'ai')
.replace(/e/g, 'enter')
.replace(/i/g, 'imes')
.replace(/o/g, 'ober')
.replace(/u/g, 'ufat');
}

two issues here
.replace doesn't change the original variable value. so if you do
let s = 'some';
s.replace('some', 'else');
console.log(s); // 'some'
so your function needs to reassign the value, or you can create a new one.
javascript function needs explicit returns, so if you don't return anything, it'll show up as undefined.
function trocaLetras(conteudoInput) {
conteudoInput = conteudoInput.replace(/a/g, 'ai');
conteudoInput = conteudoInput.replace(/e/g, 'enter');
conteudoInput = conteudoInput.replace(/i/g, 'imes');
conteudoInput = conteudoInput.replace(/o/g, 'ober');
conteudoInput = conteudoInput.replace(/u/g, 'ufat');
return conteudoInput;
}
const botaoCriptografar = document.getElementById('button');
botaoCriptografar.addEventListener('click', function(event){
event.preventDefault();
var texto = document.querySelector('#texto-para-coleta').value;
var textoAtualizado = trocaLetras(texto);
console.log(textoAtualizado);
});
<button id='button'>Encrypt</button>
<input id="texto-para-coleta" />

Related

How can I add a parameter into function, that is inside EventListener? [duplicate]

This question already has an answer here:
How to pass some parameters to function called in addEventListener? [duplicate]
(1 answer)
Closed 2 years ago.
My idea is to code a calculator with vanila JS, but I came into a problem. I want to solve it by binding keys and add eventlistener to each of them separately. To not repeat my code, I wanted to create a function that would do everything, with me adding just a key number as a parameter. When I run the code, it fires the function immediately, without clicking on "number two" . I know, that the problem is with the "click",getInput(two), I want to make this function work. Any ideas?
let input = document.getElementById("input").innerHTML;
const plus = document.querySelector(".plus");
const minus = document.querySelector(".minus");
const one = document.querySelector(".one");
const two = document.querySelector(".two");
const three = document.querySelector(".three");
const four = document.querySelector(".four");
const five = document.querySelector(".five");
const six = document.querySelector(".six");
const seven = document.querySelector(".seven");
const eight = document.querySelector(".eight");
const nine = document.querySelector(".nine");
const ac = document.querySelector(".ac");
function getInput(number){
console.log("i am here");
console.log(number.textContent);
if (input === 0){
input = number.textContent;
document.getElementById("input").innerHTML = input;
}
else{
input += number.textContent;
document.getElementById("input").innerHTML = input;
}
}
two.addEventListener("click",getInput(two));
ac.addEventListener("click",() =>{
input = 0;
console.log(input);
document.getElementById("input").innerHTML = input;
})
plus.addEventListener("click",() => {
console.log(plus.textContent);
input += plus.textContent;
document.getElementById("input").innerHTML= input;
});
one.addEventListener("click",()=>{
if (input === 0) {
input = one.textContent;
document.getElementById("input").innerHTML=input;
}
else {
input += one.textContent;
document.getElementById("input").innerHTML=input;
}
})
Second question, is there any easier way to detect user's input by not binding each key? (I am new to JS and this would help me a lot)
Kapaak
To fire a function with parameter inside event listener you need to create a function in event listener which executes your function with parameter:
btn.addEventListener("click", () => { yourFunction(parameter) });
To unify the event binding you can make something like this:
const numberBtns = document.querySelectorAll(".number-btns");
numberBtns.forEach( btn => btn.addEventListener(....));
and to get which number you pressed you can use dataset or refer to the value of the button:
<button data-number="1" class="number-btns" value="1">
// JS:
btn.dataset.number // = 1
btn.value // = 1

Using input value in the JavaScript function name [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 3 years ago.
I am trying to create JavaScript function dynamically and want to use input value as function name.
I tried:
function calculate(){
var dur = document.getElementById('duration').value; //example value: 1
var sum = document.getElementById('sum_insured2').value; //example value: 1000
`'show_d'+dur+'_sum'+sum();`
}
I want like this:
`show_d1_sum1000();`
I am not getting the output what I want.
You cannot dynamically call a function based on the value of variables in the manner you're attempting.
One workaround would be to put the function in an object and then use bracket notation to invoke the property, something like this:
var funcs = {
'show_d1_sum1000': function() { // 1 | 1000
console.log('foo bar');
}
}
var dur = document.getElementById('duration').value;
var sum = document.getElementById('sum_insured2').value;
funcs[`show_d${dur}_sum${sum}`]();
<input type="text" value="1" id="duration" />
<input type="text" value="1000" id="sum_insured2" />
That being said, this is not a good pattern to follow. In your case I'd suggest executing a single statically defined function which handles the values of the inputs, whatever they may be.
What about trying this:
console.log('show_d' + dur.toString() + '_sum' + sum.toString());
In order to create a method dynamically by this name try this:
var name = 'show_d' + dur.toString() + '_sum' + sum.toString();
var f = new Function('name', 'return alert("hello world");');
and call the method using f()
If you have already a method in your window with the same name then try accessing it like this:
window[name](anyArguments);

Why is console giving full jsFiddle link? [duplicate]

This question already has answers here:
this.href vs $(this).attr('href')
(3 answers)
Closed 5 years ago.
I wrote a little function which basically says to check if some text is exactly this or that:
function doSelect(text) {
return $wikiDOM.find(".infobox th").filter(function() {
return $(this).text() === text;
});
}
The I run this in order to get the last string after /wiki/ of some links like Geum River, Korea
let pattern = new RegExp('^\/wiki\/');
doSelect("Location").siblings('td').find('a').map(function(i, el) {
return console.log(el.href.replace(pattern, ''));
});
But when I check in console I get the whole jsFiddle link
https://fiddle.jshell.net/wiki/Geum_River
https://fiddle.jshell.net/wiki/Korea
I'd expect
Geum_River
Korea
The issue is because you're using the href attribute of the <a>. By doing this you retrieve the full absolute path of the URI, ie: https://fiddle.jshell.net/wiki/Geum_River instead of the relative path: /wiki/Geum_River
To change this behavior, use the attribute value directly, using attr():
let pattern = new RegExp('^\/wiki\/');
doSelect("Location").siblings('td').find('a').map(function(i, el) {
var result = $(this).attr('href').replace(pattern, '');
console.log(result);
return result;
});
Also double check that you're using map() correctly. It's intention is to create an array, but you're not doing anything with it's response. It would be worth using each() instead without the return if all you want to do is loop through the selected elements:
let pattern = new RegExp('^\/wiki\/');
doSelect("Location").siblings('td').find('a').each(function(i, el) {
var result = $(this).attr('href').replace(pattern, '');
console.log(result);
});
You can also try like this:
//let pattern = new RegExp('^\/wiki\/');
doSelect("Location").siblings('td').find('a').each(function(i, el) {
var name = $(this).attr('href').split('wiki/')[1].trim();
console.log(result);
});

How to pass parameters from async function in javascript? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I am trying to pass two values to a function from two async functions and I am not sure how to proceed. Here is the code:
var btcPriceInUSD;
var priceExchangeMXN;
var btcLink = "https://blockchain.info/ticker";
var exchangeRateLink = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%29&env=store://datatables.org/alltableswithkeys&format=json";
//Get btc price in USD
$.getJSON(btcLink, function(btcData)
{
btcPriceInUSD = btcData.USD.last;
//document.write(btcPriceInUSD);
});
//Get current USD/MXN exchange rate
$.getJSON(exchangeRateLink, function(exchangeData)
{
priceExchangeMXN = exchangeData.query.results.rate.Rate;
//document.write(priceExchangeMXN);
});
//Convert btc price to MXN
function convertToMXN(btc,toMXN){
var result = parseFloat(btc) * parseFloat(toMXN);
document.write(result);
}
convertToMXN(btcPriceInUSD,priceExchangeMXN)
I know the issue is that I am calling the function outside of the async ones so it is not recieving the numbers and it is giving me a NAN (not a number) but I don't know how I would correctly pass those two parameters that are each retrieved in different functions, is it possible to combine the btcPriceInUSD and priceExchangeMXN in one and call it from there?
Thanks in advance!
Try using $.when() , .then() , substituting returning value at complete function for declaring variables outside scope of asynchronous functions ; also adding an error handler
$.when($.getJSON(btcLink, function(btcData) {
return btcData.USD.last
})
, $.getJSON(exchangeRateLink, function(exchangeData) {
return exchangeData.query.results.rate.Rate
}))
.then(convertToMXN, function err() {console.log(arguments)})
try this (simply chaining the ajax calls and finally calling the method when both values are available)
var btcPriceInUSD;
var priceExchangeMXN;
var btcLink = "https://blockchain.info/ticker";
var exchangeRateLink = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%29&env=store://datatables.org/alltableswithkeys&format=json";
//Get btc price in USD
$.getJSON(btcLink, function(btcData)
{
btcPriceInUSD = btcData.USD.last;
//document.write(btcPriceInUSD);
//Get current USD/MXN exchange rate
$.getJSON(exchangeRateLink, function(exchangeData)
{
priceExchangeMXN = exchangeData.query.results.rate.Rate;
//document.write(priceExchangeMXN);
convertToMXN(btcPriceInUSD,priceExchangeMXN);
});
});
//Convert btc price to MXN
function convertToMXN(btc,toMXN){
var result = parseFloat(btc) * parseFloat(toMXN);
document.write(result);
}

JSON parsing syntax impossible [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 8 years ago.
I need to rotate a DIV, but that is not the problem I am facing, it is JSON parsing,
I want to be able to get the proper attr value from the variable rotateAttrSet but I want to get it according to the browser type
I can do var rotateAttr = rSET.FF;, but I can't do var rotateAttr = rSET.brwShort;
Is there a way to make this work?
again, I am not looking for ways to rotate the DIV, I just want to know if there is a way to get the JSON work by a variable (like .brwShort below)
Thanks
<script>
var rotateAttrSet = '{"IE":"-ms-transform","FF":"-moz-transform","CR":"-webkit-transform","SF":"-webkit-transform","OP":"-o-transform","WC3":"transform"}';
function rotator(o)
{
var o = $(o);
var angle = 0;
var rSET = parseJSON(rotateAttrSet);
var brwShort = "FF";//getBrowser().split(";")[2];
var rotateAttr = rSET.brwShort;
//alert(rotateAttr);
//o.removeAttr("onClick");
setInterval(function(){
angle++;
if(angle == 360) angle = 0;
o.text(angle);
o.css(rotateAttr, "rotate("+angle+"deg)");
}, 10);
}
function parseJSON(s)
{
return eval('('+s+')');
}
</script>
You need to use the browser short as a key as follows:
var brwShort = "FF";//getBrowser().split(";")[2];
var rotateAttr = rSET[brwShort];
Otherwise, it is actually looking for a property on the object with a key of "brwShort", which doesn't exist on your object.

Categories