String Split not working - javascript

I'm having a problem with splitting strings in Javascript in Max/MSP.
outlet is the Max/MSP version of printf etc.
The string splits weirdly, but it seems to only output both words comma seperated.
function sample_callback(args) // Callback
{
var keyword=args;
var trackname=keyword.toString().split(" ");
var name = trackname[0]; // trackname[1] outputs nothing.
outlet(0, name);
}
Any help is greatly received.

Big thanks to Aaron Kurtzhals . Hopefully the upvote in the comment counts towards your rep!
A simple overlooked checking of what the string is helped me out. oops. The working code is now..
function sample_callback(args) // Callback
{
var keyword=args.toString();
var trackname=keyword.split(",");
var name = trackname[0];
outlet(0, name);
}
Cheers

function sample_callback(args) // Callback
{
var keyword=args.toString()`enter code here`;
var trackname=keyword.toString().split(" ");
var name = trackname[0]; // trackname[1] outputs nothing.
outlet(0, name);
}

Related

How to get the first 3 digits from a cell

So I have got a column and i want to get the first 3 digits only from it and store them in a function called wnS using the split function or any other method that would work. I want to get the first three digits before "_"
I tried doing this but it didn't work, and I also kept getting "TypeError: wnC.split is not a function"
var ssh = ssPO.getSheetByName("PO for OR (East).csv")
wnC = ssh.getRange("N2:N");
var wnS = wnC.split("_");
I would really appreciate an answer
If you need more info please let me know
Thank you.
After you define range, you have to get the values.
function first_3_digs (){
var ssh = ssPO.getSheetByName("PO for OR (East).csv")
var wnC = ssh.getRange("N2:N");
var values = wnC.getValues();
const first_3_digs = values.filter(r => {
if(r.toString().includes('_')){return r;}
}).map(r=> r.toString().split('_')[0]);
console.log(first_3_digs)
}
const cell = "(303) 987-4567";
const first3 = cell.match(/\d{3}/)[0];
//result:303
String method match()
regular expression
BTW: you can test methods like this very easily in the console.log in the browsers developer tools.

Javascript Math.log() help wanted

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.

How to create dynamic regex in javascript

I want to use $htppBackend to mock some service. My problem is some of service url have parameter, ex: http://domain/service1?param1=a&param2=b
I need an regex which can reconize http://domain/service1<whatever> is correct for http://domain/service1?param1=a&param2=b. One thing, the first part http://domain/service1 is not a constant, it can be http://domain/service2/sth/anything.
Please help. Thanks.
Edit:
I put my code here to make it easy to understand.
I have 4 api urls:
angular
.module('moduleName')
.constant('getApi', {
attrList: 'http://domain/setup/attrList',
eventList: 'http://domain/setup/eventList',
vcList: 'http://domain/api/list1',
getRaDetails: 'http://domain/abc/getDetails?raId={0}&bookId={1}'
});
With attrList, eventList and vcList, they are ok with
$httpBackend.whenGET(getApi.attrList).respond(responseObject);
$httpBackend.whenGET(getApi.eventList).respond(responseObject);
$httpBackend.whenGET(getApi.vcList).respond(responseObject);.
But the last one getRaDetails, it doesn't work with
$httpBackend.whenGET(getApi.getRaDetails).respond(responseObject); because raId and bookId have different value each times.
Now I need a regex to make this rule - $httpBackend.whenGET(getApi.getRaDetails).respond(responseObject); works with all raId and bookId value.
Hope it can explain my question more clearly. Thanks
I need an regex which can reconize http://domain/service1 is
correct for http://domain/service1?param1=a&param2=b
I don't think a regex is required here. Just simply check
var stringPattern = "http://domain/service1";
var input = "http://domain/service1?param1=a&param2=b";
if ( input.indexOf( stringPattern ) == 0 )
{
alert( "correct" );
}
else
{
alert( "Incorrect" );
}
So, if you are parsing Urls, it's best to use the URL object in JavaScript:
var input = 'http://domain/abc/getDetails?raId={0}&bookId={1}';
var test = 'http://domain/abc/getDetails';
var testUrl = new URL(test);
var inputUrl = new URL(input);
then test the various bits:
if(testUrl.pathname === inputUrl.pathname){
// they both have /abc/getDetails as the path
}
This's my working code:
_(getApis).each(function (api) {
var val = api.value.split('?')[0].replace(/\//g, '\\/'),
reg = new RegExp(val);
$httpBackend.whenGET(reg).respond(dummy[api.key]);
});
Thanks all.

d3.format thousand separator on variables?

Hello I'm yet again stuck on d3...
I'd like to know how to use a thousand seperator on a variable all the examples I've managed to find seem to be on static data.
This is what I've tried so far:
d3.csv("OrderValueToday.csv", function(obj) {
var text = 'Today = £';
var totalSales = text + d3.format(",") + obj[0].Today;
svgLabel = d3.select("#label").append("h2")
.text (totalSales);
});
However it just outputs a load a stuff on the webpage this is it:
Today = £function (n){var e=d;if(m&&n%1)return"";var u=0>n||0===n&&0>1/n?(n=-n,"-"):a; if(0>p){var c=Zo.formatPrefix(n,h);n=c.scale(n),e=c.symbol+d}else n*=p;n=g(n,h);var x=n.lastIndexOf("."),M=0>x?n:n.substring(0,x),_=0>x?"":t+n.substring(x+1);!s&&f&&(M=i(M));var b=v.length+M.length+_.length+(y?0:u.length),w=l>b?new Array(b=l-b+1).join(r):"";return y&&(M=i(w+M)),u+=v,n=M+_,("<"===o?u+n+w:">"===o?w+u+n:"^"===o?w.substring(0,b>>=1)+u+n+w.substring(b):u+(y?n:w+n))+e}20000
So all I want is to be able to make the totalSales value have thousand separators so like 20,000 everything else I've tried doesnt do anything. I've read this https://github.com/mbostock/d3/wiki/Formatting but didnt see what I could do for my scenario.
Any help would be greatly appreciated. Cheers
Specifying a d3.format returns a formatting function, which you must then call as a function, passing in the number to be formatted as an argument:
var myNumber = 22400;
d3.format(',')(myNumber); // returns '22,400'
Sometimes you will see a format function stored as a variable like this:
var commaFormat = d3.format(',');
commaFormat(1234567); // returns '1,234,567'
In your case, you could do the following:
var totalSales = text + d3.format(',')(obj[0].Today);

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