RegExpr and variable - javascript

I have just one question maybe stupid (like every day)
var word = []; (an array with 100 words for example)
var tab = []; // resultat
var root = "test";
var debut = "Anti";
var reg1=new RegExp("^"+debut + "+." + root,"g")
for(var i = 0;i<word.length; i++){
// a word begin with Anti and contain test pls
if (word[i].match(reg1)){ยด
tab.push(word[i])
}
}
console.log(tab.join(', ');
but it is dont work, i dont know how to use variable with regexpr, thanks, sorry for my english

var r = new RegExp('anti.*esis', 'ig')
document.write('antithesis'.match(r), '<br/>') // ["antithesis"]
document.write('antihero'.match(r), '<br/>') // null

Here is the code, but is used the test() instead of match()
var word=["yea","antiboyahtest","antigssjshbztest"];
var debut="anti";
var root="test";
var reg=new RegExp("^"+debut+".*"+root,"g");
var tabs=[];
for(i in word){
if(reg.test(word[i])){
tabs.push(word[i]);
}
}
alert(tabs);

The solution using RegExp.test and Array.filter functions:
var word = ['Antitest', 'Antidot', 'Anti-next-test', 'testAnti'],
root = "test", debut = "Anti",
reg1 = new RegExp("^"+debut + ".*?" + root, "g");
var result = word.filter(function (w) {
return reg1.test(w);
});
console.log(result); // ["Antitest", "Anti-next-test"]
Also, there's an additional approach using Array.indexOf function without any regex which will give the same result:
...
var result = word.filter(function (w) {
return w.indexOf(debut) === 0 && w.indexOf(root) !== -1;
});

Related

Javascript pull data from string?

I have a long URL that contains some data that I need to pull. I am able to get the end of the URL by doing this:
var data = window.location.hash;
When I do alert(data); I receive a long string like this:
#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600
note in the example the access token is not valid, just random numbers I input for example purpose
Now that I have that long string stored in a variable, how can I parse out just the access token value, so everything in between the first '=' and '&. So this is what I need out of the string:
0u2389ruq892hqjru3h289r3u892ru3892r32235423
I was reading up on php explode, and others java script specific stuff like strip but couldn't get them to function as needed. Thanks guys.
DEMO (look in your debug console)
You will want to split the string by the token '&' first to get your key/value pairs:
var kvpairs = document.location.hash.substring(1).split('&');
Then, you will want to split each kvpair into a key and a value:
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != 'access_token')
continue;
console.log(v); //Here's your access token.
}
Here is a version wrapped into a function that you can use easily:
function getParam(hash, key) {
var kvpairs = hash.substring(1).split('&');
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != key)
continue;
return v;
}
return null;
}
Usage:
getParam(document.location.hash, 'access_token');
data.split("&")[0].split("=")[1]
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
var requiredValue = str.split('&')[0].split('=')[1];
I'd use regex in case value=key pair changes position
var data = "#token_type=Bearer&access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&expires_in=3600";
RegExp("access_token=([A-Za-z0-9]*)&").exec(data)[1];
output
"0u2389ruq892hqjru3h289r3u892ru3892r32235423"
Looks like I'm a bit late on this. Here's my attempt at a version that parses URL parameters into a map and gets any param by name.
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
function urlToMap(url){
var startIndex = Math.max(url.lastIndexOf("#"), url.lastIndexOf("?"));
url = url.substr(startIndex+1);
var result = {};
url.split("&").forEach(function(pair){
var x = pair.split("=");
result[x[0]]=x[1];
});
return result;
}
function getParam(url, name){
return urlToMap(url)[name];
}
console.log(getParam(str, "access_token"));
To answer to your question directly (what's between this and that), you would need to use indexOf and substring functions.
Here's a little piece of code for you.
function whatsBetween (_strToSearch, _leftText, _rightText) {
var leftPos = _strToSearch.indexOf(_leftText) + _leftText.length;
var rightPos = _strToSearch.indexOf(_rightText, leftPos);
if (leftPos >= 0 && leftPos < rightPos)
return _strToSearch.substring(leftPos, rightPos);
return "";
}
Usage:
alert(whatsBetween, data,"=","#");
That said, I'd rather go with a function like crush's...
try this
var data = window.location.hash;
var d1 = Array();
d1 = data.split("&")
var myFilteredData = Array();
for( var i=0;i<d1.length;i++ )
{
var d2 = d1[i].split("=");
myFilteredData.push(d2[1]); //Taking String after '='
}
I hope it helps you.

Writing a function that "solves" an equation

I want to write a function which will allow me to "solve" an equation in js.
what I want (not in a programming language):
function f(x) { 1 + x * x }
var z = 2
var y = f(z) //y will be 5 as a number
what I have written in JS:
function P(cfg) { ....
this.equation = "1 + x";
....};
P.prototype.eqn = function(x) {
var tmp = eval(this.equation);
return tmp;
};
....
P.prototype.draw = function() {....
for(var i = 0; i < z; i++)
ctx.lineTo(i, this.eqn(i));
....};
also I've read that using eval in a loop is probably not a good idea, but I have not figured out another way (yet) (JS beginner)...
The problem with this code is, that at least in FF the var tmp will STILL contain the string from this.equation instead of the calculated value.
I would appreciate any further insight very much!
Thank you for your time :)
EDIT: because my question was not formulated very well:
after the execution of line
var tmp = eval(this.equation);
the var tmp will hold a STRING which equals the string this.equation, instead of the desired solution y value.
Also I do not mean solve but evaluate, thanks for that tip :)
Based on your example, I'd say that you want to "evaluate an expression", rather than "solve an equation". For evaluating an expression, you can probably find many tutorials. I'll break it down in brief though. You need to do a few steps.
Starting with your string "1 + x * x", you need to break it into tokens. Specifically, break it down into: "1", "+", "x", "*", "x". At this point, you can substitute your variables ("x") for their literal values ("2"), giving you "1", "+", "2", "*", "2"
Now you need to parse the expression. Based on order of operations PEMDAS you need to create a tree data structure, where parenthetical clauses (stuff surrounded by parenthesis) are executed first, multiplication and division next, and then additions and subtraction last. Parsing is often not an easy task, and you may want to put together a simpler BNF grammar (though you can probably find a grammar for simple math expressions with some googling).
Next, walk the tree, depth first, evaluating the operations as you go up the tree. Once you get to the top of the tree, you have your solution.
If instead you want to "solve an equation", you're going to need something much more sophisticated, like Sage
I have used this expression evaluator before. It seemed to work very well. It allows you to pass expressions into a Parser that returns a function object that can then evaluate inputs.
var expr = Parser.parse("2 ^ x");
expr.evaluate({ x: 3 }); // 8
It supports trig functions (sin, cos, ect...) and other handy built in functions such as abs & ciel.
var expr = Parser.parse("sin(x/2) + cos(x/2)")
expr.evaluate({x: Math.PI / 2}); // 1
Examples: http://silentmatt.com/javascript-expression-evaluator/
Code: https://github.com/silentmatt/js-expression-eval
Note that this lib does not use eval().
Not sure I entirely understand your question but how about:
var makeFunctionOfX = function(src) {
return Function('x', 'return ' + src);
};
Then you can say things like:
var g = makeFunctionOfX('2 * x')
var y = g(3); // y contains 6
The great advantage of this over eval is that the Function we create has no magic ability to see variables in the scope (hence the need to explicitly pass it x as a parameter name).
Using eval is safe if you trust the input from the user, and works just fine. (I have no idea what you mean by "the var tmp will still have the string this.equation".)
function FuncCreator(eqn){ this.eqn = eqn }
FuncCreator.prototype.run = function(x,y,z){ return eval(this.eqn) }
var add1 = new FuncCreator('1+x');
var result = add1.run(41); // 42
var complex = new FuncCreator('Math.sin(x*y) / Math.cos(z)');
var result = complex.run(3,4,5); // -1.891591285331882
If you don't trust the user input, you'll need to actually parse the input and process it yourself. This is non-trivial.
You can use the expression parser from the math.js library and do something like this:
var parser = math.parser();
var f = parser.eval('function f(x) = 1 + x * x');
// use the created function f in expressions:
parser.eval('z = 2'); // 2
parser.eval('y = f(z)'); // 5
// or use the created function f in JavaScript:
var z = 2; // 2
var y = f(z); // 5
Creating functions in math.js is quite currently limited, loops and blocks needed to define more extensive functions are not yet supported.
This is an old thread, but I wrote this equation calculator, this doesn't solve algebraic equations though. There is however a function that will allow you to provide an array containing assigned variables. But this doesn't solve for variables that don't have an assigned value.
I probably haven't permuted every test case scenario, but it seems to work pretty decent.
Edit: This would have to be modified to handle negative numbers. Other than that... works fine.
Here is a fiddle
<!doctype html>
<html>
<head>
<title>Javascript Equation Calculator</title>
</head>
<body>
<input type="button" onclick="main()" value="calculate"><br>
<input type="text" id="userinput"><br>
<span id="result">Ready.</span><br>
<script>
function Calculator(){}
String.prototype.replaceLast = function (what, replacement)
{
var pcs = this.split(what);
var lastPc = pcs.pop();
return pcs.join(what) + replacement + lastPc;
};
function inS(substr, str){return (str.indexOf(substr) > -1);}
function arrayValueOrToken(arr, key, token)
{
if(key in arr)
{
return arr[key];
}
return token;
}
function reduceEquation(inputStr)
{
console.log("reduceEquation Executed-----");
while(hasNest(inputStr))
{
if(hasNest(inputStr))
{
inputStr = inputStr.replace(")(",')*(');
for(var i=0;i<=9;i++)
{
inputStr = inputStr.replace(i+"(",i+'*(');
inputStr = inputStr.replace(")"+i,')*'+i);
}
var s = inputStr.lastIndexOf("(");
var e = 0;
for(i=s;i,inputStr.length;i++){if(inputStr[i]==")"){e=i+1;break;}}
var eq = inputStr.substring(s,e);
var replace = eq;
eq = eq.replace(/[()]/g, '');
var substitution = solveEquation(eq);
inputStr = inputStr.replaceLast(replace,substitution);
}
}
return inputStr;
}
function solveEquation(eq)
{
console.log("solveEquation Executed-----");
eq = doFirstOrder(eq);
eq = doLastOrder(eq);
return eq;
}
function doFirstOrder(eq)
{
console.log("doFirstOrder Executed-----");
for(var i=0;i<eq.length;i++)
{
if(eq[i]=="*"){eq = solve(eq,"*");return doFirstOrder(eq);}
if(eq[i]=='/'){eq = solve(eq,'/');return doFirstOrder(eq);}
}
return eq;
}
function doLastOrder(eq)
{
console.log("doLastOrder Executed-----");
for(var i=0;i<eq.length;i++)
{
if(eq[i]=="+"){eq = solve(eq,"+");return doLastOrder(eq);}
if(eq[i]=="-"){eq = solve(eq,"-");return doLastOrder(eq);}
}
return eq;
}
function solve(eq, operator)
{
var setOp = operator;
console.log("solve Executed-----");
var buildEq = "",var1 = true,done = false,char="";
var operators = "+-/*";
var ops = operators.replace(operator, '').split('');
var a=ops[0];
var b=ops[1];
var c=ops[2];
for(var i=0;i<eq.length;i++)
{
char = eq[i];
switch(true)
{
case(char==operator):if(var1===true){var1 = false;}else{done = true;}break;
case(char==a):
case(char==b):
case(char==c):if(var1){char = ""; buildEq = "";}else{done = true;}
}
if(done){break;}
buildEq = buildEq + char;
}
var parts = parts = buildEq.split(operator);
var solution = null;
if(operator=="+"){solution = parseFloat(parts[0]) + parseFloat(parts[1]);}
if(operator=="-"){solution = parseFloat(parts[0]) - parseFloat(parts[1]);}
if(operator=="*"){solution = parseFloat(parts[0]) * parseFloat(parts[1]);}
if(operator=="/"){solution = parseFloat(parts[0]) / parseFloat(parts[1]);}
return eq.replace(buildEq, solution);
}
function hasNest(inputStr){return inS("(",inputStr);}
function allNestsComplete(inputStr)
{
var oC = 0, cC = 0,char="";
for(var i=0;i<inputStr.length;i++){char = inputStr[i];if(char=="("){oC+=1;}if(char==")"){cC+=1;}}
return (oC==cC);
}
Calculator.prototype.calc = function(inputStr)
{
console.log("Calc Executed-----");
inputStr = inputStr.replace(/ /g, "");
inputStr = inputStr.replace(/\\/g, '/');
inputStr = inputStr.replace(/x/g, "*")
inputStr = inputStr.replace(/X/g, "*")
if(!allNestsComplete(inputStr)){return "Nested operations not opened/closed properly.";}
inputStr=reduceEquation(inputStr);
inputStr = solveEquation(inputStr);
return inputStr;
};
Calculator.prototype.calcWithVars = function(inputList)
{
if(inputList.length < 2){return "One or more missing arguments!";}
var vars = [];
var assocVars = [];
var lastVarIndex = inputList.length - 2;
var i = 0;
var inputStr = inputList[inputList.length-1];
for(i=0;i<=lastVarIndex;i++)
{
vars.push(inputList[i].replace(/ /g, ""));
}
for(i=0;i<=vars.length-1;i++)
{
var vParts = vars[i].split("=");
var vName = vParts[0];
var vValue = vParts[1];
assocVars[vName] = vValue;
}
inputStr = inputStr.replace(/ /g, "");
var eqVars = inputStr.replace(/\s+/g, ' ').replace(/[^a-zA-Z-]/g, ' ').replace(/\s\s+/g, ' ');
if(inS(" ", eqVars))
{
eqVars = eqVars.split(" ");
}
else{eqVars = [eqVars];}
eqVars.sort(function(a, b){return a.length - a.length;});
var tempTokens = [];
var tempCount = 1;
for(i=0;i<eqVars.length;i++)
{
var eqVname = eqVars[i];
var substitution = arrayValueOrToken(assocVars, eqVname, "<unknown>");
if(substitution != "<unknown>")
{
inputStr = inputStr.replace(eqVname,substitution);
}
else
{
var tempToken = "#______#"+tempCount+"#______#";
tempCount++;
tempTokens.push(tempToken + "?" + eqVname);
inputStr = inputStr.replace(eqVname,tempToken);
}
}
for(i=0;i<tempTokens.length;i++)
{
var tokenSet = tempTokens[i];
var tokenParts = tokenSet.split("?");
var token = tokenParts[0];
var variableName = tokenParts[1];
inputStr = inputStr.replace(token,variableName);
}
var answerName = "<unknown>";
var eq = inputStr;
if(inS("=", inputStr))
{
var eqParts = inputStr.split("=");
answerName = eqParts[0];
eq = eqParts[1];
}
eq = this.calc(eq);
var result = [];
for(i=0;i<eqVars.length;i++)
{
var v = arrayValueOrToken(assocVars, eqVars[i], "<unknown>");
if(v != "<unknown>")
{
result.push(assocVars[eqVars[i]]);
}
}
result.push(eq);
return result;
};
function main()
{
var calculator = new Calculator();
elUserInput = document.getElementById('userinput');
console.log("input: "+ elUserInput.value);
elResult = document.getElementById('result');
equation = elUserInput.value;
result = calculator.calc(equation);
console.log("result: "+ result);
elResult.innerHTML = result;
}
</script>
</body>
</html>

Want to get specific value from string

I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#.
I want to get last string vwemployees through RegExp or from any JavaScript function.
Please suggest a way to do this in JavaScript.
You can use the split function:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);
// Output: vwemployees
The reason for -2 is because of the trailing #. If there was no trailing #, it would be -1.
Here's a JSFiddle.
var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;
if you're sure the string will be separated by "#" then you can split on # and take the last entry... I'm stripping off the last #, if it's there, before splitting the string.
var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array
if(parts.length > 0){
var result = parts[parts.length-1];
}
Try something like this:
String.prototype.between = function(prefix, suffix) {
s = this;
var i = s.indexOf(prefix);
if (i >= 0) {
s = s.substring(i + prefix.length);
}
else {
return '';
}
if (suffix) {
i = s.indexOf(suffix);
if (i >= 0) {
s = s.substring(0, i);
}
else {
return '';
}
}
return s;
}
No magic numbers:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);
jsfiddle example

Find text between two characters and for each, do something

I have a file full with text in the following format:
(ignoring the fact that it is CSS) I need to get the string between the two | characters and each time, do something:
<div id="unused">
|#main|
#header|
.bananas|
#nav|
etc
</div>
The code I have is this:
var test_str = $('#unused').text();
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
//I want to do something with each string here
This just gets the first string. How can I add logic in there to do something for each string?
You can use split method to get array of strings between |
Live Demo
arr = $('#unused').text().split('|');
You can split like
var my_splitted_var = $('#unused').text().split('|');
One way;
$.each($("#unused").text().split("|"), function(ix, val) {
val = $.trim(val); //remove \r|\n
if (val !== "")
alert(val);
});
One way :
var test_str = $('#unused').text();
while(!test_str.indexOf('|'))
{
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
test_str = test_str.slice(end_pos,test_str.length);
}
RegExp-Version:
LIVE DEMO (jsfiddle.net)
var trimmedHtml = $("#unused").html().replace(/\s/g, '');
var result = new Array();
var regExp = /\|(.+?)(?=\|)/g;
var match = regExp.exec(trimmedHtml);
result.push(match[1]);
while (match != null) {
match = regExp.exec(trimmedHtml);
if (match != null) result.push(match[1]);
}
alert(result);
So you only get the elements BETWEEN the pipes (|).
In my example I pushed every matching result to an array. You can now iterate over it to get your result.

Transform a string into array using javascript

I have a string like this:
string = "locations[0][street]=street&locations[0][street_no]=
34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
What must I do with this string so i can play with locations[][] as I wish?
You could write a parser:
var myStr = "locations[0][street]=street&locations[0][street_no]=34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
function parseArray(str) {
var arr = new Array();
var tmp = myStr.split('&');
var lastIdx;
for (var i = 0; i < tmp.length; i++) {
var parts = tmp[i].split('=');
var m = parts[0].match(/\[[\w]+\]/g);
var idx = m[0].substring(1, m[0].length - 1);
var key = m[1].substring(1, m[1].length - 1);
if (lastIdx != idx) {
lastIdx = idx;
arr.push({});
}
arr[idx * 1][key] = parts[1];
}
return arr;
}
var myArr = parseArray(myStr);
As Shadow wizard said, using split and eval seems to be the solution.
You need to initialize locations first, if you want to avoid an error.
stringArray=string.split("&");
for (var i=0;i<stringArray.length;i++){
eval(stringArray[i]);
}
However, you might need to pay attention to what street and street_no are.
As is, it will produce an error because street is not defined.
Edit: and you'll need to fully initialize locations with as many item as you'll have to avoid an error.

Categories