Javascript: strip first and last \ from regExp variable - javascript

I'm cobbling together a script which maps mouse X,Y coordinates to an axis grid. The resulting variable will then be passed to CSS transform property. I'm getting all the numbers I need, but I'm stuck on the last part, which is to remove the \ around the result, which has been converted to a regular expression so as to allow for negative integers.
var resultX = RegExp(Math.round(mousePos.x/6.6) -60);
resultX = resultX.replace(/\//g,'');
The final stage (stripping the slashes) throws an error no matter how I do it. I've tried encapsulating .replace in a function, and using return, but I continue to get the same error:
TypeError: 'undefined' is not a function (evaluating
'resultX.replace(///g,'')')
I'm stuck, and haven't been able to find the solution anywhere. Perhaps the problem is that my variable isn't a true string? Or maybe someone has a suggestion for a better way to allow for negative integers.
JS fiddle:
http://jsfiddle.net/wAKnY/

Like JayC mentioned in the comments, there doesn't seem to be a reason to convert to a RegExp in the first place, so I would just recommend removing the enclosing RegExp().
However, if you require that for some reason that isn't apparent here, you can then call toString() on it to enable the replace function to behave correctly:
resultX = resultX.toString().replace(/\//g,'');

As JayC said, you don't need a regexp in the first place.
var resultX = (Math.round(mousePos.x/6.6)-60).toString;

This works:
resultX = resultX.toString().replace(/\//g, '');
resultY = resultY.toString().replace(/\//g, '');

Related

using .substring after .replace is creating an error sometimes, how could I properly structure the substring so that it always works?

I'm getting an error with my code below. I am trying to make a calculator, and I am using strings as input and typecasting in order to solve. The calculator was working fine, but now I am trying to add an ans button to allow for having equations based on previous answer. I am having an issue with the substrings now, and in equations where ans comes first like 'ans+88" I get NaN as a result and 88 turns into undefined. But when I switch the substring parameters it messes it up for other types of equations as described in the comments below.
link to repository
else if(equation.indexOf("+") != -1){
//this finds the the index of +
let pInd = equation.indexOf("+")
/*before I added this, it worked properly, firstValue would get the firstvalue
secondvalue would get the second value and it added correctly
the point of the if statement is to replace ans with props.prevResult which is
the previous answer from the previous entered equation. After it replaces it
removes the whitespace*/
if(equation.includes("ᴀɴs")){
equation = equation.replace(/ᴀɴs/gi, String(props.prevResult))
//my attempt to remove whitespace since i thought it might be the issue
// but now I'm pretty sure the issue is with substring.
equation = equation.replace(/\s/g, '')
}
equation = String(equation)
firstVal = equation.substring(0,pInd)
//this line is where the error seems to come from
secondVal = equation.substring(pInd+1,equation.length)
/* when ans is first such as in 'ans + 9" 9 becomes undefined ans stays
correct. I tried replacing it with pInd+1, equation.length-1, but that
made it so that equations like '9+ans' were cut short,
and regular ('1+55') equations also broke.*/
result = parseFloat(firstVal)+parseFloat(secondVal)
props.setInput(result)
props.setPrevResult(result)
setResultGot(true)
}
The solution #james gave solved the issue, the position of the + sign was obviously going to change after I replaced ans, so that line just had to be moved to after the replacement, silly mistake, I appreciate the help.

converting a string to float doesn't work

I got a variable Javascrpit which has a number as a string in this case 0.84. I'm trying to convert it into a float but when I try to it appears a 0 as float instead the 0.84.
I'm using this:
var pot="0.84";
var asd = parseFloat(pot);
console.log(asd);
EDIT:
This is not exactly the example. I recover data from the HTML and it works for other numbers but not for this. It is difficult to explain my problem exactly. It is a lot of code and works for other numbers so don't know exactly.
Your input is not "0.84". If you test with that, you will get the correct answer. Your input has something else inside, like spaces, for example:
"0 .84"
This should be the solution:
parseFloat(pod.replace(/ /g, ""))
I have tried this example on my end and it completely worked. However, you can try to instead input the string value directly into the parse float() function and it should print our your expected value. If you still want to assign the parsefloat() to a variable, then try to either rewrite the code or re-open your IDE because the code should work.
var pot = "0.84"
console.log(parseFloat(pot))
or you can just write it in one line
console.log(parseFloat("0.84"))

Javascript regex match doesn't run correctly

okay I give up. Here's my code:
var re = /href="(http.*\.jpg)"/g;
var mp3s = body.match(re);
it finds pictures, but it returns href="http://www.picture.com/smthg.jpg"
instead of returning http://www.picture.com/smthg.jpg
any idea why?
The result from match() is actually an object.
I think you need to access the first element on that object.
For example:
body.match(re)[1]
This is where the actual result is kept.
Shameless self-promotion:
I've written a small guide for me, I can never remember how to use these either. It's here: http://queirozf.com/reminders/javascript-regular-expressions-usage-reminder
try
var re = /(http.*\.jpg)/g;
var mp3s = body.match(re);
since you don't need the href.
You want to match the regular expression, but then return just the portion in brackets.
To do this, call the regular expressions exec method. For example:
var body = 'stuff stuff morestuff href="http://www.picture.com/smthg.jpg" and some more stuff';
var re = /href="(http.*\.jpg)"/g;
var regexResults = re.exec(body);
var mp3s = regexResults[1];
alert(mp3s);
Having given you this answer, I must implore you to find a different way to solve this problem. You cannot parse HTML using regular expressions. No matter how sophisticated your regular expression gets, there will be a legal HTML example which will break it.

Regex: find whatever comes after one thing before another thing

I want to find anything that comes after s= and before & or the end of the string. For example, if the string is
t=qwerty&s=hello&p=3
I want to get hello. And if the string is
t=qwerty&s=hello
I also want to get hello
Thank you!
\bs=([^&]+) and grabbing $1should be good enough, no?
edit: added word anchor! Otherwise it would also match for herpies, dongles...
Why don't you try something that was generically aimed at parsing query strings? That way, you can assume you won't run into the obvious next hurdle while reinventing the wheel.
jQuery has the query object for that (see JavaScript query string)
Or you can google a bit:
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
looks useful; for example with
http://www.bloggingdeveloper.com?author=bloggingdeveloper
you want to get the "author" querystring's value:
var author_value = getQuerystring('author');
The simplest way to do this is with a selector s=([^&]*)&. The inside of the parentheses has [^&] to prevent it from grabbing hello&p=3 of there were another field after p.
You can also use the following expression, based on the solution provided here, which finds all characters between the two given strings:
(?<=s=)(.*)(?=&)
In your case you may need to slightly modify it to account for the "end of the string" option (there are several ways to do it, especially when you can use simple code manipulations such as manually adding a & character to the end of the string before running the regex).

Removing comma for value with Javascript

thanks for looking my questions, I can't find the way to remove the comma with javascript. So I have problem at removing comma from page with java-script, Adding Comma for output is fine i guess, but for removing comma for value, the function is not working for me.
The source code is : http://jsfiddle.net/Q5CwM/2/
Please let me know, thanks again.
I have no idea what your code is trying to do overall, but you can fix this function that removes commas:
function checkNumeric(objName) {
var lstLetters = objName;
var lstReplace = lstLetters.replace(/\,/g,'');
}
by changing it to this:
function removeCommas(str) {
return(str.replace(/,/g,''));
}
You weren't returning the changed string from the function and I changed the name of the function and parameters to represent what it does.
str.replace returns the changed string. It does not change the string you started with so in order to do something with the result of the replacement, you have to either return that from the function or assign it to some other string. As you had it, nothing was happening with the replaced string so the function did nothing.

Categories