I searched around and after running this through a few RegEx builders it seems to do what I want... but when I actually try and implement it it never seems to work.
This is the expression I'm using: (?<=\[)[0-9]+(?:\.[0-9]*)?(?=\])
From my understanding, this is supposed to match any numbers between the []
symbols. I am unconcerned if it is a true float, positive or negative, or any of that, because it is predetermined.
The purpose of this is that I have a set number of prebuilt <select>
tags that the website has already built. I need to loop through all of the select tags and get the c开发者_开发问答urrently selected option, and inside of that match the number between []
.
<select>
<option>Stuff [193.33]</option>
<option>Stuff2 [19232l.39393]</option>
</select>
Something like...
$('#content_area').$('input:select').change(function(){
$('#content_area').$('select option:selected').each(function(){}
I am unaware as to why,
- the expression gives me a syntax error even if I just return it in an alert, and
- how would I construct the loop?
Your jQuery code is completely wrong.
You're probably trying to write
$('#content_area select').change(function() {
var value = $(this).val();
});
a) You should put this as the value of your option, e.g.
<select>
<option value="193.33">Stuff [193.33]</option>
<option value="19232l.39393">Stuff2 [19232l.39393]</option>
</select>
b) If you can't change your HTML, then the regex you want is:
/\[\d+(\.\d+)?\]/
You can't use what you have for several reasons, including the fact that most JS interpreters do not not support positive lookbehind assertions. Because of this, we'll have to capture the square brackets and then ignore them, like so:
$('foo option:selected').each(function(){
var float = /\[(\d+(\.\d+)?)\]/.exec(this.value)[1] * 1;
});
According to this article Javascript does not support lookbehind. Would this expression work for you?
(?:\[)([0-9]+(?:\.[0-9]*)?)(?:\])
EDIT: Or, more concisely \[(\d+(?:\.\d*)?)\]
(Thanks to Phrogz for pointing this out)
EDIT2: To address the jQuery bit, maybe something like this would work (lifted from the jQuery :selected
documentation):
$("select").change(function () {
$("select option:selected").each(function () {
var value = $(this).text();
// Do regex magic
});
});
There is a great tool here to test your regex's
http://www.regextester.com/
精彩评论