Javascript Math.log() help wanted - javascript

World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax

Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);

I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.

Related

Compare two variable string in JavaScript

i am trying to compare two strings in javascript. below is my code
var statuss = document.getElementById("status").innerHTML;
//alert(statuss);
var s =statuss.toString();
var ss= "Active";
if (s === "Active"){
alert ('match');
}
else {
alert ('do not match');
}
why am i getting the output " do not match" when it should have been 'match' since when i did
alert ('document.getElementById("status").innerHTML');
i got the output: Active.
So basically both variable should have matched.. why am getting the opposite?
You might want to try the following
var s = statuss.toString().trim();
The most likely explanation is that your HTML also contains whitespace at the beginning and/or end.

trying to find words that begin with a

I am writing some code to find words in paragraphs that begin with the letter "a". I was wondering if there was a shortcut that I could put inside of a variable. I do know about the startsWith() function but that does not work for what i'm trying to do. Here's what I have so far. I'm trying to use the match method and .innerText to read the paragraphs.
function processText() {
var totalNumberOfWords = document.getElementById('p')
var wordsBegginingWithA = 0;
var wordsEndingWithW = 0;
var wordsFourLettersLong = 0;
var hyphenatedWords = 0;
}
<p><button onClick="processText();">Process</button></p>
<p id="data"></p>
<p>The thousand injuries of Fortunato I had borne as I best could; but when he ventured upon insult, I vowed revenge. You, who so well know the nature of my soul, will not suppose, however, that I gave utterance to a threat.
<span style='font-style:italic;'>At
length</span> I would be avenged; this was a point definitely settled--but the very definitiveness with which it was resolved precluded the idea of risk. I must not only punish, but punish with impunity. A wrong is unredressed when retribution
overtakes its redresser. It is equally unredressed when the avenger fails to make himself felt as such to him who has done the wrong.</p>
You can get the inner text of the p element - split it at the spaces to get the words - pass the words through a function to see if the first letter is "a" and if so, increment a count.
processText();
function processText() {
var p = document.querySelector('p').innerText;
var totalWords = p.split(' ');
var wordsBegginingWithA = 0;
totalWords.forEach(function(word){
if ( beginsWithA(word) ) {
wordsBegginingWithA++
};
})
console.log(wordsBegginingWithA); // gives 5
}
function beginsWithA(word){
return word.toLowerCase().charAt(0) == 'a';
}
<p>Apples and oranges are fruit while red and blue are colors</p>
You can use:
[variablename].match(/(?<!\w)a\w*/ig)!=null? a.match(/(?<!\w)a\w*/ig).length:0; to detect what words starting with what letter (in example it was a).
And:
[variablename].match(/\S+/g)!=null? a.match(/\S+/g).length:0;
to detect word count.
function processText() {
var a = document.getElementById('p').innerText;
var b = a.match(/(?<!\w)a\w*/ig)!=null? a.match(/(?<!\w)a\w*/ig).length:0;
var word= a.match(/\S+/g)!=null? a.match(/\S+/g).length:0;
console.log('Text: ',a,'\nA starting word: ', b, '\nWord count: ',word);
}
processText();
<span id="p">Apple is super delicious. An ant is as good as my cat which favors a pear than fish. I'm going to test them all at once.</span>
Explanation: .match would return all value which matches the expression given.
Notice that I also used conditional (ternary) operator to detect whether or not the Regex will return a null value if no match were returned. If it's returning null then it would result in 0 (:0) if it's returning another value than null then it would return the count (.length).
More info related to Regular expression: https://www.rexegg.com/regex-quickstart.html
function processText() {
let pp = document.getElementById('root')
console.log(pp.innerHTML.match(/(?<!\w)a\w*/g))
return pp.innerHTML.match(/(?<!\w)a\w*/g);
}
processText()
<p id='root'>this is a apple</p>
Using the result of indexOf, 0 is the equivalent to startsWith
var str = document.getElementById("myTextarea").value;
var keyword = document.getElementById("myInput").value;
var n = str.indexOf(keyword);`
Working sample in this fiddle.
HTH

Formatting input type="text" in JS

I have a text field with type='text' and I am trying to format the text with commas. Example: 500000000 would become 500,000,000.
I have the following code:
function addComma(values) {
values.value = values.value.replace(",", "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
However, it's printing 5,000,0,0,0,000 and the formatting is off for some reason. I also tried .toLocaleString(), but that doesn't seem to work either. What am I doing wrong here?
I was referred to a few other posts on Stack Overflow, but nothing seems to work out.
function addComma(values) {
const v = values.value && new Number(values.value.replace(/,/g,''));
values.value = v.toLocaleString();
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
You can do this by converting the number to a string, then manually iterating over each character and find places where a comma is needed.
function formatNumber(number) {
var str = number.toString();
var offset = str.length % 3;
var newStr = '';
for (var i = 0; i < str.length; i++) {
if (i > 0 && i % 3 === offset) {
newStr += ',';
}
newStr += str[i];
}
console.log(str, '=>', newStr);
}
formatNumber(5);
formatNumber(50);
formatNumber(500);
formatNumber(5000);
formatNumber(50000);
formatNumber(500000);
formatNumber(5000000);
I'd recommend using a change event rather than a keyup event as change will only update the value when the input is no longer the focus. If you use keyup the code will try and reinterpret the new string you add back to the input as a number and throw an error.
Here's the code using toLocaleString (just press tab after adding the number as if to move to the next input box):
const values = document.querySelector('#values');
values.addEventListener('change', handleChange, false);
function handleChange(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
values.value = formatted;
}
<input id="values" type="text">
The other answers posted before this one using the input field are ok to show how it works, but they are bugged as soon as you enter a new number when it has formatted to a string using toLocaleString(). For that reason I added the toNumber() function to be complete. In the example below I preform the following steps:
When user fills in a number in the input field and leaves the input field: Call toString(e) and make from the entered number a formatted string.
If the user again selects the input field, call toNumber(e) and format it back to a number.
This makes sure you won't get NaN when reselecting or will become completely unusable.
The NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number.
It is still possible to add text in it, this will result in NaN as text cannot be formatted to a number. This could be filtered out in the toString(e) when necessary. I did this in the example below by adding if (formatted !== 'NaN') {} Only when it's not NaN it will set the value to the new formatted number. Else it won't do anything. Please note: a number with dots is a string in this case so wont work either.
const values = document.querySelector('#values');
values.addEventListener('click', toNumber, false);
values.addEventListener('focusout', toString, false);
function toNumber(e) {
const value = e.target.value;
const unformatted = value.replace(/\D/g,'');
values.value = unformatted;
}
function toString(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
if (formatted !== 'NaN') {
values.value = formatted;
}
}
<input id="values" type="text">
To fix that, you can also remove my addition and add a filter before the toString(e) does it's thing and filter the dots, text etc. so only the numbers remain.

Unable to Get Output From While Loop in Javascript

I'm working on my final project of the Winter 2017 quarter to demonstrate how to use Regular Expressions in both C# and JavaScript code behind pages. I've got the C# version of my demonstration program done, but the JavaScript version is making me pull what little hair I have left on my head out (no small achievement since I got a fresh buzz cut this morning!). The problem involves not getting any output after applying a Regular Expression in a While loop to get each instance of the expression and printing it out.
On my HTML page I have an input textarea, seven radio buttons, an output textarea, and two buttons underneath (one button is to move the output text to the input area to perform multiple iterations of applying expressions, and the other button to clear all textareas for starting from scratch). Each radio button links to a function that applies a regular expression to the text in the input area. Five of my seven functions work; the sixth is the one I can't figure out, and the seventh is essentially the same but with a slightly different RegEx pattern, so if I fix the sixth function, the seventh function will be a snap.
(I tried to insert/upload a JPG of the front end, but the photo upload doesn't seem to be working. Hopefully you get the drift of what I've set up.)
Here are my problem children from my JS code behind:
// RegEx_Demo_JS.js - code behind for RegEx_Demo_JS
var inputString; // Global variable for the input from the input text box.
var pattern; // Global variable for the regular expression.
var result; // Global variable for the result of applying the regular expression to the user input.
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder()
{
var strings = [];
this.append = function (string)
{
string = verify(string);
if (string.length > 0) strings[strings.length] = string;
}
this.appendLine = function (string)
{
string = verify(string);
if (this.isEmpty())
{
if (string.length > 0) strings[strings.length] = string;
else return;
}
else strings[strings.length] = string.length > 0 ? "\r\n" + string : "\r\n";
}
this.clear = function () { strings = []; };
this.isEmpty = function () { return strings.length == 0; };
this.toString = function () { return strings.join(""); };
var verify = function (string)
{
if (!defined(string)) return "";
if (getType(string) != getType(new String())) return String(string);
return string;
}
var defined = function (el)
{
// Changed per Ryan O'Hara's comment:
return el != null && typeof(el) != "undefined";
}
var getType = function (instance)
{
if (!defined(instance.constructor)) throw Error("Unexpected object type");
var type = String(instance.constructor).match(/function\s+(\w+)/);
return defined(type) ? type[1] : "undefined";
}
}
Within the code of the second radio button (which will be the seventh and last function to complete), I tested the ScriptBuilder with data in a local variable, and it ran successfully and produced output into the output textarea. But I get no output from this next function that invokes a While loop:
function RegEx_Match_TheOnly_AllInstances()
{
inputString = document.getElementById("txtUserInput").value;
pattern = /(\s+the\s+)/ig; // Using an Flag (/i) to select either lowercase or uppercase version. Finds first occurrence either as a standalone word or inside a word.
//result = pattern.exec(inputString); // Finds the first index location
var arrResult; // Array for the results of the search.
var sb = getStringBuilder(); // Variable to hold iterations of the result and the text
while ((arrResult = pattern.exec(inputString)) !==null)
{
sb.appendLine = "Match: " + arrResult[0] ;
}
document.getElementById("txtRegExOutput").value = sb.toString();
/* Original code from C# version:
// string pattern = #"\s+(?i)the\s+"; // Same as above, but using Option construct for case insensitive search.
string pattern = #"(^|\s+)(?i)the(\W|\s+)";
MatchCollection matches = Regex.Matches(userTextInput, pattern);
StringBuilder outputString = new StringBuilder();
foreach (Match match in matches)
{
string outputRegExs = "Match: " + "\"" + match.Value + "\"" + " at index [" + match.Index + ","
+ (match.Index + match.Length) + "]" + "\n";
outputString.Append(outputRegExs);
}
txtRegExOutput.Text = outputString.ToString();
*/
} // End RegEx_Match_The_AllInstances
I left the commented code in to show what I had used in the C# code behind version to illustrate what I'm trying to accomplish.
The test input/string I used for this function is:
Don’t go there. If you want to be the Man, you have to beat The Man.
That should return two hits. Ideally, I want it to show the word that it found and the index where it found the word, but at this point I'd be happy to just get some output showing every instance it found, and then build on that with the index and possibly the lastIndex.
So, is my problem in my While loop, the way I'm applying the StringBuilder, or a combination of the two? I know the StringBuilder code works, at least when not being used in a loop and using some test data from the site I found that code. And the code for simply finding the first instance of "the" as a standalone or inside another word does work and returns output, but that doesn't use a loop.
I've looked through Stack Overflow and several other JavaScript websites for inspiration, but nothing I've tried so far has worked. I appreciate any help anyone can provide! (If you need me to post any other code, please advise and I'll be happy to oblige.)

ExtJS 4.1.1: Evaluating a field in a grid

I'm struggling with a ExtJS 4.1.1 grid that has editable cells (CellEditing plugin).
A person should be able to type a mathematic formula into the cell and it should generate the result into the field's value. For example: If a user types (320*10)/4 the return should be 800. Or similar if the user types (320m*10cm)/4 the function should strip the non-mathematical characters from the formula and then calculate it.
I was looking to replace (or match) with a RegExp, but I cannot seem to get it to work. It keeps returning NaN and when I do console.log(e.value); it returns only the originalValue and not the value that I need.
I don't have much code to attach:
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
console.log(str);
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
var numCalc = Number(eval(strCalc));
console.log(numCalc);
return numCalc;
},
Which returns: str=321 strCalc=null numCalc=0 when I type 321*2.
Any help appreciated,
GR.
Update:
Based on input by Paul Schroeder, I created this:
onGridValidateEdit : function(editor,e,opts) {
var str = e.record.get(e.field).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
console.log(typeof numCalc);
console.log(numCalc);
return numCalc;
},
Which calculates the number, but I am unable to print it back to the grid itself. It shows up as "NaN" even though in console it shows typeof=number and value=800.
Final code:
Here's the final code that worked:
onGridValidateEdit : function(editor,e,opts) {
var fldName = e.field;
var str = e.record.get(fldName).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
e.record.set(fldName,numCalc);
},
Lets break this code down.
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
What listener is this code being used in? This is very important for us to know, here's how I set up my listeners in the plugin:
listeners: {
edit: function(editor, e){
var record = e.record;
var str = record.get("your data_index of the value");
}
}
Setting it up this way works for me, So lets move on to:
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
at which point strCalc=null, this is also correct. str.match returns null because your regex does not match anything in the string. What I think you want to do instead is this:
var strCalc = str.replace(/[^0-9+*-]/g, "");
console.log(strCalc);
This changes it to replace all characters in the string that aren't your equation operators and numbers. After that I think it should work for whole numbers. I think that you may actually want decimal numbers too, but I can't think of the regex for that off the top of my head (the . needs to be escaped somehow), but it should be simple enough to find in a google search.

Categories