I've got something like that:
[#parameter='value']
and
[#parameter]
and I need regexp to parse both cases,
in first returns parameter & value in the second only parameter
Now, I've got something like that
"[#short-name='shorty']".match(/\[\#(.*)\=\'(.*)\'\]/)
which returns
["[#short-name='shorty']", "short-name", "shorty"]
its great but only in first case, please help
EDIT:
I just figured that probably two matches could be replaced by one so if it's possible, a little extension of current solution will be great.
match something like:
PARENT//CHILD[#parameter='value']
or
PARENT//CHILD[#parameter]
or
PARENT//CHILD
should returns
[ parent, child, parameter, value ]
[ parent, child, parameter ]
[ parent, child ]
Thanks a lot!
EDIT 2:
Allright it's easy
/([A-Z]+)\/\/([A-Z]+)(\[#([^=\]]*)(?:='(.*)'])?)?/
if it's possible to do it easier, please show me how
This will work for your general case:
/\[#([^=\]]*)(?:='(.*)'])?/
I removed a lot of the unnecessary escaping you were doing. The value is in parentheses (not captured because of ?:) and then made optional. The \[#.* has to be changed to \[#[^=\]] so that it will only try to capture up to the equals or the close brace (either of which may be there).
You can also update this to correctly match quotes, or even omit them
/\[#([^=\]]*)(?:=(['"]?)(.*)\2])?/
EDIT: You can also match multiple values per line using a similar expression; just add .*? for the capture of the value.
"[#short-name='shorty'] [#long-name=\"longy\"] [#longest]".replace(
/\[#([^=\]]*)(?:=(['"]?)(.*?)\2])?/g,
function () { console.log(arguments[1], arguments[3]); })
This will yield "short-name, shorty", "long-name longy", "longest undefined"
Let the second part be optional.
Put some spaces to best view.
"[#short-name]".match(/\[\#(.*) (\=\'(.*)\')? \]/)
Wrapping the code with parentheses and adding a ? will do the trick.
http://metahtml.sourceforge.net/documentation/regex/regex_3.mhtml#SEC14
Related
I have a very specific problem concerning a regular expression matching in Javascript. I'm trying to match a piece of source code, more specifically a portion here:
<TD WIDTH=100% ALIGN=right>World Boards | Olympa - Trade | <b>Bump when Yasir...</b></TD>
The part I'm trying to match is boardid=106121">Olympa - Trade</a>, the part I actually need is "Olympa". So I use the following line of JS code to get a match and have "Olympa" returned:
var world = document.documentElement.innerHTML.match('/boardid=[0-9]+">([A-Z][a-z]+)( - Trade){0,1}<\/a>/i')[1];
the ( - Trade) part is optional in my problem, hence the {0,1} in the regex.
There's also no easier way to narrow down the code by e.g. getElementsByTagName, so searching the complete source code is my only option.
Now here's the funny thing. I have used two online regex matchers (of which one was for JS-regex specifically) to test my regex against the complete source code. Both times, it had a match and returned "Olympa" exactly as it should have. However, when I have Chrome include the script on the actual page, it gives the following error:
Error in event handler for 'undefined': Cannot read property '1' of null TypeError: Cannot read property '1' of null
Obviously, the first part of my line returns "null" because it does not find a match, and taking [1] of "null" doesn't work.
I figured I might not be doing the match on the source code, but when I let the script output document.documentElement.innerHTML to the console, it outputs the complete source code.
I see no reason why this regex fails, so I must be overlooking something very silly. Does anyone else see the problem?
All help appreciated,
Kenneth
You're putting your regular expression inside a string. It should not be inside a string.
var world = document.documentElement.innerHTML.match(/boardid=[0-9]+">([A-Z][a-z]+)( - Trade){0,1}<\/a>/i)[1];
Another thing — it appears you have a document object, in which case all this HTML is already parsed for you, and you can take advantage of that instead of reinventing a fragile wheel.
var element = document.querySelector('a[href*="boardid="]');
var world = element.textContent;
(This assumes that you don't need <=IE8 support. If you do, there remains a better way, though.)
(P.S. ? is shorthand for {0,1}.)
$('.selector:contains("'+ filterText +'")').show()
for showing div based on the bases of string "search" now it's working fine with the exact character case of lowercase and upper case
now here i googled my issue many links i found and in almost all sites and event stackoverflow i found similar code like below code..
jQuery.expr[':'].Contains = function(a,i,m){
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())> -1;
};
so here i am interested in this a, i, and m parameters
also that how can i use the $(".selector":contains('"+ search +"')).show() with any case sensitivity ( lowercase or upper case ).
the use this code with what i have written will be better one
and alternative solutions about free text search with key press will be the best on but but but
no use of third party plugins.
i think You guys need to refer bellow link
http://jsfiddle.net/potherca/ympBL/
There are many ways to filter an element that contains the give text. One form is the following.
$(".selector:contains('"+ search +"')").show();
But this is case sensitive. If you'd like a case insensitive match, you may want to write a custom filter method by extending the filter expressions of jQuery, like below.
jQuery.extend(jQuery.expr[':'], {
icontains: function(elem, index, arr){
return jQuery(elem).text().toLowerCase().indexOf(arr[3].toLowerCase()) !== -1
}
});
In the method you create for any jQuery expression, you are given three arguments. The first is the DOM element for that particular iteration. Second is the index of the DOM element relative to the original collection the expression was called on. Last is an array similar to what you'd get from a RegExp exec method call. The full expression is the first array position, second is the text from the selector between the colon and opening paren, and the last is the string that occurs within the parens.
Then use it as:
$(".selector:icontains('" + search + "')").show();
I would suggest you learn to use filter(fn) which offers lots of control over how you filter elements.
$(".selector").filter(function(){
return $(this).toLowerCase().indexOf(search.toLowerCase()) >-1;
}).show();
I'm trying to serialise my array but I'm getting nothing in the log.
I want all checkboxes called color[] but not the first one.
I've tried:
$("input[name='color[]:not(:first)']").serialize();
But this logs as blank.
The following works but includes the first one, so it must be a problem with the not part.
$("input[name='color[]']").serialize();
Your attribute equal selector is wrong $("input[name='color[]:not(:first)']")
$("input[name='color[]']:not(:first)").serialize();
The selector you are using is wrong.
Finish ] after the name=value selector.
$("input[name='color[]']:not(:first)").serialize();
Here are the mistakes highlighted:
$("input[name='color[]:not(:first)']").serialize();
// ^ finish selector here
Please use this
$("input[name='color[]']:not(:first)").serialize();
Anyway to convert innerHTML to bbcode?
Something like that
document.getelementbyid.('div').bbcode
or a way to replace %0A to [br] in the current link of the page?
I've tried this with no luck
window.location.replace('%0A', '[br]');
.bbcode is not a valid function (or property how you've written it), unless of course you are including some kind of external library that you haven't told us about?
With regards to the window.location.replace you are not assigning it to anything so where would you expect to see the change? Though you should also use
window.location.href.replace(needle,haystack);
see http://jsfiddle.net/9LGRP/1/ for a quick example or replace working to replace the word "show" with "foo"
Please note the syntax is slightly different for global replacements e.g
window.location.href.replace(/foo/g, 'bar')
would replace all instances of foo. You can also add the modifier 'i' after the 'g' to ignore case https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
Perhaps you need to elaborate more on your question and show more context if this doesn't address your needs.
I'm a beginner in jquery and ajax. While i was going through some example online, i came across the following piece of code and wondered what exactly it does.
lines = newLine.split('#');
jQuery.each(lines, function(lineNo, line) {
eval("linedata = " + line);
data.push(linedata);
});
I'm not a programmer, but just trying to understand its functionality. Can anyone help me?
The each function iterates over an array which is supplied as the first parameter. During each iteration the index and element are passed into a function that is performed. The function is passed as the second parameter to the each function.
Read more on the jQuery Documentation
In the example you have provided a string newLine is split into an array using # as the delimiter.
The each function then iterates over the newly created array, assigning the value of each element to a variable linedata and pushes linedata onto another array.
This could be more easily achieved with the following, since the call to eval is unnecessary:
jQuery.each(lines, function(lineNo, line) {
data.push(line);
});
I pretended, for a moment, that I was a new programmer. This is how you should go about looking into things from here on out:
1.) Ok, I don't know what this first line is doing. It's splitting something (based on the split word). Hmmm let's Google for "split javascript". This is the first thing that comes up. From here, you may be wondering what a String is, so you would search for that as well).
2.) Ok so now I know that splitting a String gives me an array (again you probably looked this up by this step) of the newLine substrings that were separated by the # character. Cool. So let's look into what jQuery.each does. I google "jQuery.each" and this is the first thing that comes up.
Awesome! Now you understand what a String is, an Array, the split function from String as well as what jQuery.each is. :D
EDIT: As you move forward, you'll realize that W3C is generally an inferior source of information. I simply linked to it since it was literally the first thing that came up when I Googled "split javascript". Overall it does the job for giving you a good overview of certain things when you're learning them for the first time.