Do mathematic operation according to symbol in element.innerText - javascript

I am preparing calculator and I would like to have only one function, to get the result according to input value
const equals=document.getElementById("equals");
equals.addEventListener('click',()=>getResult(a));
a= symbol.innerText
function getResult(a){
result.innerText = +calculations1.innerText a +calculations2.innerText;
> }
Where a could be either +, -, %, /, *.
Do you think it is possible to do this if a is stored as a string in element.innerText to do one function depending what stays there?
I try to make my function cleaner

Related

how to calculate numbers in a string in javascript?

I'm getting some inputs from the user and saving them in a div tag just like a calculator works, for example, a user puts 100-50+30 then I store it in div tag at and when user clicks on go button I want to show him the result which is 80.
I tried parseint and number since string contains operators like + / * these don't work
var a = document.querySelector(".output").innerHTML;
You can simply use eval, but for security reasons I would recommend removing everything from user input except for digits and permitted operators before evaluating the expression:
const input = '100-50+30 [some malicious code]'
const result = eval(input.replace(/[^0-9\+\-\*\/]/g, ''));
console.log(result)
Use eval() function
var expression = '100-50+30';
console.log(eval(expression));
The eval() function evaluates JavaScript code represented as a string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

javascript regex look behind to replace a character

I have a long strings of code that look something like
hs2^Ȁ_^HELLO_x_fs2^Ȁ_^WORLD_x_gn3^Ȁ_^HOME_x_gs3^Ȁ…
I need to do a replace. A hex character is used repeatedly Ȁ and there’s always a ^ in front of it. I need to change the number that appears before each ^Ȁ Reduce those numbers by 1. So the final result will be…
hs1^Ȁ_^HELLO_x_fs1^Ȁ_^WORLD_x_gn2^Ȁ_^HOME_x_gs2^Ȁ…
I’m really only dealing with two numbers here, 2 or 3, so the code would read something like this…
If (any number directly before ^Ȁ ==2) change it to 1
else if (any number directly before ^Ȁ ==3) change it to 2
I’ve heard of something called a “lookback” or “look behind” is that what’s needed here?
You can use replace with a callback function, which will be used to replace each occurrence using your own logic:
var str = "hs2^Ȁ_^HELLO_x_fs2^Ȁ_^WORLD_x_gn3^Ȁ_^HOME_x_gs3^Ȁ";
var res = str.replace(/\d(?=\^Ȁ)/g, num => --num);
console.log(res);
In the regex above, you'll notice this: (?=...). It's a positive lookahead, as suggested by #revo. It allows you to match ^Ȁ, but avoid passing it to your callback function. Only the digit (\d) will be passed, and thus, replaced.

Alternative to lookbehind in js

I am trying to use javascript to do text replacements for variables with the follow format #variable (yes I know it is bad practice, but sadly it's data from an external system so I cannot change it).
The problem is that I need to ensure that it also works if there are mail addresses in the text.
Therefor it needs to match #variable but not test#example.com. If it was in another language I would simply use something like, but js does not support lookbehind.
text.replace(/(?<!\w)#[\w]+/g, replacement);
'#var' matches #var
'#var bar' matches #var
'bar#var' does not match
'bar2#var' does not match
Any javascript way of doing this using regex?
Here is an example of the expected result using negative lookbehind
https://regex101.com/r/orCEGE/1
It's not entirely clear what exactly you want to replace, but here's a fairly generic method:
const text = "#A foo#bar#baz #var#asdf.#Z";
const result = text.replace(/#(\w+)/g,
(m0, m1, pos, str) => {
if (pos > 0 && /\w/.test(str.charAt(pos-1))) {
return m0;
}
return "{replacement for " + m1 + "}";
}
);
console.log(result);
The replacement function gets not just the matched parts of the string, but also the position where the match occurred. This match position can be used to make further decisions (e.g. whether the matched string should be returned unchanged (as in return m0;)).

Is there a way to have `toHaveBeenCalledWith` match a regular expression?

I have a function that appends a random number an then calls another function. I want to check that it was called with the text passed in and match any random number. I'd like to be able to pass a Regex without Jest literally matching the Regex. Something like:
const typeFn = jest.fn();
function type (text) {
typeFn(text + Math.random());
})
type('hello')
expect(typeFn).toHaveBeenCalledWith(/hello\d+/)
You can use one of the helper functions in expect instead of an actual value:
expect(typeFn).toHaveBeenCalledWith(expect.stringMatching(/hello\d+/));
Here's a live example: https://repl.it/#marzelin/FrighteningCapitalConferences

Change javascript regex divider character

I have a simple JS question.
I have this code, and what I need is cut the textbox value every two characters (this works fine), but I want to change the comma with the column.
My actual result is:
stringtest - st,ri,ng,te,st
and I want this:
stringtest - st:ri:ng:te:st
my code is:
function test() {
var textboxtext= $("#textbox").val();
var splitted = textboxtext.match(/.{2}|.{1,2}/g);
alert("B8:27:EB:" + splitted)
The problem is not with the regex, but with how you're converting the result array to a string. When the JavaScript engine needs to convert an array to a string (which is done implicitly when you use the binary + operator with an string on either side), it calls the toString() method, which basically just calls the join() method, which returns a string with each element of the array converted to a string, and separated by commas.
But you can call the join method yourself and specify what character you'd like it to use as a separator, like this:
alert("B8:27:EB:" + splitted.join(':'));
On a side note, you can simplify your regex to .{1,2}, which is exactly the same as what you had previously:
var splitted = textboxtext.match(/.{1,2}/g);

Categories