What exactly is this jQuery / Regex snippet doing? - javascript

I'm not very good with RegEx, and am trying to learn. I have inherited a project which contains the following line of code:
function findCourseIdFromForm(where) {
var matchRegex = /\[course-[0-9]*\]/;
var replaceRegex = /\[|\]|[a-z]|\-/g;
return $(".cnumber", where.parent()).attr("name").match( matchRegex )[0].replace( replaceRegex,"" );
}
I'm not entirely sure what this piece of code is trying to do, but I know that it is causing issues on my page. I'm using jQuery validator and this specific component (".cnumber") is causing the validation to fail and I'm not entirely sure why, so some insight into this line is appreciated.
The .cnumber field in the HTML looks like this:
<input type="hidden" name="courses[course-0][cnumber]" class="cnumber" />

This function takes where node, gets its parent, finds .cnumber node within the parent, then takes [course-0] part and finally remove all [, ], -, and lowercase letters.
So the function returns the number that stands after [course- part, or empty string if there is no number

It strips out [, ], lowercase letters and - from the name attribute in the tag, presumably to return the course number.

It just get the course number. In you example, it return 0

Related

How to get a value from page source code from a function tag?

here is the function from the source code
function dosubmit()
{
if (getObj("Frm_Username").value == "")
{
getObj("errmsg").innerHTML = "Username cannot be empty.";
getObj("myLayer").style.visibility = "visible" ;
return;
}
else
{
getObj("LoginId").disabled = true;
getObj("Frm_Logintoken").value = "3";
document.fLogin.submit();
}
}
i want to get the value of getObj("Frm_Logintoken") as i can't pull the value
from #Frm_Logintoken
using document.getElementById("#Frm_Logintoken") this gives me null
because Frm_Logintoken only gets it's value when i click submit .
<input type="hidden" name="Frm_Logintoken" id="Frm_Logintoken" value="">
full page code
i found this online /getObj\("Frm_Logintoken"\).value = "(.*)";/g but when i run it ... it gives me the same line again ! it's full code
another regular expression i found but don't even know how to use it
Example of a regular expression to search:
before_egrep='N1:getObj("Frm_Logintoken").value = "(\w+)"'
Here, N1 is assigned the value of the back reference - the
expression in parentheses. \w + denotes the main compound characters,
this is a synonym for "[_[:alnum:]]". Once again - pay attention to
the brackets - this is the back link. At the same time, there are also
parentheses in the source code fragment - they need to be escaped
i am trying to make an auto login script that works in the background like it
doesn't show the user the login form page but the only the page after it
and i have found this code online too but don't know what's about
it contains xhr .
the line that Attracted my attention is
/getObj\("Frm_Logintoken"\).value = "(.*)";/g
when i run it ... it gives me the line again !
some notes :
i have tried document.getElementById("Frm_Logintoken").value but it gives me empty "" because
Frm_Logintoken only gets it's value when i click submit .
the page will not even accept the correct password if the Frm_Logintoken token value isn't the same as one in the page.
the Frm_Logintoken is a token generated by the page and it basically increment by one on each successful login.
I'm not so sure about suggestion of an expression for helping or ameliorating to help solving your problem, yet if we wish to extract certain attributes and values from the proposed input tag, we would be likely starting with an expression similar to:
name="(.+?)"|id="(.+?)"|value="(.+)?"
which uses alternation to simultaneously collect values of certain attributes, if so would be desired.
Demo
RegEx
If this expression wasn't desired and you wish to modify it, please visit this link at regex101.com.
RegEx Circuit
jex.im visualizes regular expressions:
To get your value you might use a capturing group ([^"]+) and a negated character class:
\bgetObj\("Frm_Logintoken"\)\.value = "([^"]+)";
Regex demo | Javascript demo
For example:
let str = `getObj("Frm_Logintoken").value = "3";`;
let pattern =/\bgetObj\("Frm_Logintoken"\)\.value = "([^"]+)";/;
console.log(str.match(pattern)[1]); //3

Use only one of the characters in regular expression javascript

I guess that should be smth very easy, but I'm stuck with that for at least 2 hours and I think it's better to ask the question here.
So, I've got a reg expression /&t=(\d*)$/g and it works fine while it is not ?t instead of &t in url. I've tried different combinations like /\?|&t=(\d*)$/g ; /\?t=(\d*)$|/&t=(\d*)$/g ; /(&|\?)t=(\d*)$/g and various others. But haven't got the expected result which is /\?t=(\d*)$/g or /&t=(\d*)$/g url part (whatever is placed to input).
Thx for response. I think need to put some details here. I'm actually working on this peace of code
var formValue = $.trim($("#v").val());
var formValueTime = /&t=(\d*)$/g.exec(formValue);
if (formValueTime && formValueTime.length > 1) {
formValueTime = parseInt(formValueTime[1], 10);
formValue = formValue.replace(/&t=\d*$/g, "");
}
and I want to get the t value whether reference passed with &t or ?t in references like youtu.be/hTWKbfoikeg?t=82 or similar one youtu.be/hTWKbfoikeg&t=82
To replace, you may use
var formValue = "some?some=more&t=1234"; // $.trim($("#v").val());
var formValueTime;
formValue = formValue.replace(/[&?]t=(\d*)$/g, function($0,$1) {
formValueTime = parseInt($1,10);
return '';
});
console.log(formValueTime, formValue);
To grab the value, you may use
/[?&]t=(\d*)$/g.exec(formValue);
Pattern details
[?&] - a character class matching ? or &
t= - t= substring
(\d*) - Group 1 matching zero or more digits
$ - end of string
/\?t=(\d*)|\&t=(\d*)$/g
you inverted the escape character for the second RegEx.
http://regexr.com/3gcnu
I want to thank you all guys for trying to help. Special thanks to #Wiktor Stribiżew who gave the closest answer.
Now the piece of code I needed looks exactly like this:
/[?&]t=(\d*)$/g.exec(formValue);
So that's the [?&] part that solved the problem.
I use array later, so /\?t=(\d*)|\&t=(\d*)$/g doesn't help because I get an array like [t&=50,,50] when reference is & type and the correct answer [t?=50,50] when reference is ? type just because of the order of statements in RegExp.
Now, if you're looking for a piece of RegExp that picks either character in one place while the rest of RegExp remains the same you may use smth like this [?&] for the example where wanted characters are ? and &.

Can someone explain what this regex do?

It's part of code where javascript should watch for some price and match if it's lover than required, but i don't understand regex quite well and it's obvious that the error is in there.
So on a website i have price like
<div class="item_price_now"> $ 1,34 </div>
And on javascript part code looks like this
var maxprice = '0.98';
var itemprice = document.getElementByClassName('item_price_now');
var i = 0;
var currentprice = itemprice[i].innerHTML.replace(/\s+/g, ' ');
currentprice = currentprice.substring(2);
if (currentprice > maxprice)
{ do some code }
else
{ do some other code }
But this doesn't work, i assume that part of error is in regex, with this i don't get any values, i tried to change it to something like this
(\S+\w)
And it's outputing something (actually i get output of 1,34 ) but still can't match it with maxprice variable.
Can someone explain me what regex above means or at least point me in some direction. Thanks.
/\s+/g means "match any space/tab character that is repeated one of more times over the entire string".
Hence it's replacing any multiple whitespaces/tabs with a single whitespace.
It seems that your problem is that you use locale strings to describe your value, as you're comparing the string 0.98 (which is casted by JS) with 1,34 (which cannot be casted by JS, as , would be a thousand seperator)

regex search a string for contents between two strings

I am trying my upmost best to get my head around regex, however not having too much luck.
I am trying to search within a string for text, I know how the string starts, and i know how the string ends, I want to return ALL the text inbetween the string including the start and end.
Start search = [{"lx":
End search = }]
i.e
[{"lx":variablehere}]
So far I have tried
/^\[\{"lx":(*?)\}\]/;
and
/(\[\{"lx":)(*)(\}\])/;
But to no real avail... can anyone assist?
Many thanks
You're probably making the mistake of believing the * is a wildcard. Use the period (.) instead and you'll be fine.
Also, are you sure you want to stipulate zero or more? If there must be a value, use + (one or more).
Javascript:
'[{"lx":variablehere}]'.match(/^\[\{"lx":(.+?)\}\]/);
The * star character multiplies the preceding character. In your case there's no such character. You should either put ., which means "any character", or something more specific like \S, which means "any non whitespace character".
Possible solution:
var s = '[{"lx":variablehere}]';
var r = /\[\{"(.*?)":(.*?)\}\]/;
var m = s.match(r);
console.log(m);
Results to this array:
[ '[{"lx":variablehere}]',
'lx',
'variablehere',
index: 0,
input: '[{"lx":variablehere}]' ]
\[\{"lx"\:(.*)\}\]
This should work for you. You can reach the captured variable by \1 notation.
Try this:
^\[\{\"lx\"\:(.*)\}\]$
all text between [{"lx": and }] you will find in backreference variable (something like \$1 , depends on programming language).

Find and get only number in string

Please help me solve this strange situation:
Here is code:
The link is so - www.blablabla.ru#3
The regex is so:
var id = window.location.href.replace(/\D/, '' );
alert(id);
The regular expression is correct - it must show only numbers ... but it's not showing numbers :-(
Can you please advice me and provide some informations on how to get only numbers in the string ?
Thanks
You're replacing only the first non-digit character with empty string. Try using:
var id = window.location.href.replace(/\D+/g, '' ); alert(id);
(Notice the "global" flag at the end of regex).
Consider using location.hash - this holds just the hashtag on the end of the url: "#42".
You can write:
var id = location.hash.substring(1);
Edit: See Kobi's answer. If you really are using the hash part of things, just use location.hash! (To self: Doh!)
But I'll leave the below in case you're doing something more complex than your example suggests.
Original answer:
As the others have said, you've left out the global flag in your replacement. But I'm worried about the expression, it's really fragile. Consider: www.37signals.com#42: Your resulting numeric string will be 3742, which probably isn't what you want. Other examples: www.blablabla.ru/user/4#3 (43), www2.blablabla.ru#3 (23), ...
How 'bout:
id = window.location.href.match(/\#(\d+)/)[1];
...which gets you the contiguous set of digits immediately following the hash mark (or undefined if there aren't any).
Use the flag /\D/g, globally replace all the instances
var id = window.location.href.replace(/\D/g, '' );
alert(id);
And /\D+/ gets better performance than /\D/g, according to Justin Johnson, which I think because of \D+ can match and replace it in one shot.

Categories

Resources