Get PHP captcha value by JavaScript - javascript

I want to make some kind of JavaScript validation. I have been using some PHP script to generate captcha code.
My Dom is:
<img src="http://examle.com/captcha_code_file.php?rand=1846368456" name="6_letters_code" id="captchaimg">
Is there a way to grab number 1846368456 and compere with input field?
Will it work something like this:
var a = document.getElementById("captchaimg");
var b = a. val();

a.val() wouldn't be valid javascript either. If the element had a value attribute the proper syntax would be a.value. To grab the source element use a.src. Then you need to parse out the random number:
var src = a.src;
var match = src.match(/rand=(\d+)$/);
var rand = match.length > 1 ? match[1] : null;
What this is doing is taking the src value and matching off the last term rand=NUMBER. Since we wrapped the \d+ in () it will match to that value in the second element of the match array.
For more information on match see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match There is also a link for regular expressions there as well.

Related

Javascript RegEx contains

I'm using Javascript RegEx to compare if a string matches a standart format.
I have this variable called inputName, which has the following format (sample):
input[name='data[product][tool_team]']
And what I want to achieve with Javascript's regex is to determine if the string has the following but contains _team in between those brackets.
I tried the following:
var inputName = "input[name='data[product][tool_team]']";
var teamPattern = /\input[name='data[product][[_team]]']/g;
var matches = inputName.match(teamPattern);
console.log(matches);
I just get null with the result I gave as an example.
To be honest, RegEx isn't really my area, so I suppose it's wrong.
A couple of things:
You need to escape [ and ] as they have special meaning in regex
You need .* (or perhaps [^[]*) in front of _team if you want to allow anything there ([^[]* means "anything but a [ repeated zero or more times)
Example if you just want to know if it matches:
var string = "input[name='data[product][tool_team]']";
var teamPattern = /input\[name='data\[product\]\[[^[]*_team\]'\]/;
console.log(teamPattern.test(string));
Example if you need to capture the xyz_team bit:
var string = "input[name='data[product][tool_team]']";
var teamPattern = /input\[name='data\[product\]\[([^[]*_team)\]'\]/;
var match = string.match(teamPattern);
console.log(match ? match[1] : "no match");
If you are trying to check for DOM elements you can use attribute contains or attribute equals selector
document.querySelectorAll("input[name*='[_team]']")

parsing image name from img tag with regex

I have an <img> tag inside a div where i want to get the image name through javascript and regex.
Now, I successfully retrieved the <img> tag as a string.
var bigImage = $(this).find('.img-container img')
var bigImageSrc = bigImage[0].src
var regx = /g\bplaceholderdefault\.jpg?\b/g
var match = bigImageSrc.match(regx)
I want this expression to see if there is placeholderdefault.jpg in the string.
By the way, bigImageSrc returns a valid string, as I checked it with typeof
Now the problem is it returns null even if bigImageSrc's value is http://localhost/yogurtbar/images/slider/placeholderdefault.jpg
I don't get why it doesn't detect placeholderdefault.jpg in the string. I tried (and produced) this regular expression in Regexr and it works.
What am I doing wrong in my code?
There is no need of regex.\
You can use indexOf. This will run faster as compared to regex:
if (bigImageSrc.indexOf('placeholderdefault.jpg') > -1) {
// Present
If you want to check it with regex:
if (/placeholderdefault\.jpg/.test(bigImageSrc)) {
// Present
}
You need to escape .
You need to remove the g present at the start.
var regx = /g\bplaceholderdefault\.jpg?\b/g;
^
|
Since there isn't a charcater g exists before p (in placeholder), your regex fails to find a match.
correct one would be,
var regx = /\bplaceholderdefault\.jpg?\b/g;
and also, I think you want to match both jpg and jpeg formats.
var regx = /\bplaceholderdefault\.jpe?g\b/g;
Easy way will be to get the image name using split()
var bigImageSrc = 'http://localhost/yogurtbar/images/slider/placeholder-default.jpg';
var filename = bigImageSrc.split("/").pop();
console.log(filename);
//output placeholder-default.jpg

Jquery data-target as string possible?

I have a data-attribute with a unique name and a number at the end.
data-target="foo-bar-n"
where n is the unique number.
I want to be able to get that number but it isn't working.
I call:
.data("target")
on the object I want the target from and It returns fine, but when I use a regex search on the results, I get a completely different number, which I suspect is because returned data is an object with other data. What I need to know is how to get that number out, or how to convert the data-attribute into a string. (I've tried toString, and that doesn't work.)
Here is my code:
var selection= window.getSelection().getRangeAt(0);
var showSelection = $(selection.commonAncestorContainer.parentNode.parentNode)
.data('target');
console.log(showSelection);
console.log(showSelection.search(/\d+/));
The console logs
#comment_for_paragraph_17
23
The program is meant to let a user select something on the page and highlight it.
If you are using jQuery 1.4.3 or later you can use
.data("target");
otherwise you must use
.attr("data-target");
But your requirement appears to be extracting a number from a formatted string parameter?
HTML:
<div id="foo" data-target="foo-bar-5"></div>
jQuery:
var num = $('#foo').data('target').split('-')[2];
Or regex:
var num = $('#foo').data('target').match(/\d+/);
Or if your requirement is specifically capture the last number in the string (eg: foo-bar-55-23 would result in '23')
var num = $('#foo').data('target').split('-').slice(-1);
// regex
var num = $('#foo').data('target').match(/\d+$/);
See fiddle
I suspect is because returned data is an object with other data.
That doesn't make any sense at all. The reason you are not getting the number in the string is because .search returns the index of the match. Use .match or .exec instead:
showSelection.match(/\d+/)[0];
/*or*/
/\d+/.exec(showSelection)[0];
Try:
.data('target').split('-').slice(-1)[0];
.split will split your string into an array with each array element being a word
.slice(-1) will return an array consisting of the last element of your array
[0] accesses the array element

Extracting strings from an input field using regular expressions and jQuery

I am trying to match a string in an input field using a regular expression /[1-9][a-zA-Z]/ and insert it into a <p> tag using jQuery.
I modified this example from the jQuery API docs to include the following if statement. When I type '1A' in the input field it works, however I want to exclude the rest of the string so that the <p> only includes the matched string portion.
$("input").keyup(function () {
if($(this).val().match(/[1-9][a-zA-Z]/)){
var value = $(this).val();
};
$("p").text(value);
}).keyup();
Did I explain that clearly? Could anyone point me in the right direction?
Much appreciated,
So what you are doing in the above code is that if the value of the input field matches the regular expression, you assign its value to <p> tag. Since, you want to assign the matched string to the <p> tag, you should do:
$("input").keyup(function () {
var match = $(this).val().match(/[1-9][a-zA-Z]/);
if(match){
var value = match[0]; // Your problem was here
};
$("p").text(value);
}).keyup();
The match method of a String returns an array containing the match if it passed or undefined if the match failed.

How can i get value with javascript regular expressions

i have following text
http://www.mydomain.com/#!/account/?id=17
and i am getting # with window.location.href which is giving me
#!/account/?id=17
now i want to extract that id value with preg_match or any regular expression because that id value is dynamic...
actually i am loading data with jquery ajax...please let me know the exact expression for getting value of id...
Try this:
"#!/account/?id=17".match(/id=(.*)/)[1]
EDIT
var result = window.location.href.match(/id=(.*)/);
match returns an array with two positions:
result[0] = all matched string ("id=17")
result[1] = first group match ("17")

Categories

Resources