Why does this jQuery code not work? - javascript

Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?

Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.

If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}

So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")

How about using the following function to read the query string parameter in JavaScript:
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];
}
and then:
alert(getQuerystring('fb'));

If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions

Related

Get string from a successful regex?

I'm trying to manipulate a string that has tested as a positive match against my regex statement.
My regex statement is /\[table=\d](.*?)\[\/table] / gmi and an example of a positive match would be [table=1]Cell 1[c]Cell 2[/table]. I'm searching for matches within a certain div, which I'll call .foo in the code below.
However, once the search comes back saying it has found a match, I want to have the section that was identified as a match returned back to me so that I can start manipulating a specific section of it, namely count the number of times [c] appears and reference the number in [table=1].
(function(regexCheck) {
var regex = /\[table=\d](.*?)\[\/table] / gmi;
$('.foo').each(function() {
var html = $(this).html();
var change = false;
while (regex[0].test(html)) {
change = true;
//Somehow return string?
}
});
})(jQuery);
I'm quite new to javascript and especially new to RegEx, so I apologise if this code is crude.
Thanks for all of your help in advance.
Use exec instead of test and keep the resulting match object:
var match;
while ((match = regex[0].exec(html)) != null) {
change = true;
// use `match[0]` for the full match, or `match[1]` and onward for capture groups
}
Simple example (since your snippet isn't runnable, I've just created a simple one instead):
var str = "test 1 test 2 test 3";
var regex = /test (\d)/g;
var match;
while ((match = regex.exec(str)) !== null) {
console.log("match = " + JSON.stringify(match));
}

Javascript regex match and get values from string

I've got a string of text which can have specific tags in it.
Example: var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';
What I'm trying to do is do a regex match against the <pause #></pause> tag.
For each tags found, in this case it's <pause 4></pause> and <pause 7></pause>. What I want is to grab the value 4 and 7, and the string length divided by for the string in between the <pause #>...</pause> tags.
What I have for now is not much.
But I cant figure out how to grab all the cases, then loop through each one and grab the values I'm looking for.
My function for this looks like this for now, it's not much:
/**
* checkTags(string)
* Just check for tags, and add them
* to the proper arrays for drawing later on
* #return string
*/
function checkTags(string) {
// Regular expresions we will use
var regex = {
pause: /<pause (.*?)>(.*?)<\/pause>/g
}
var matchedPauses = string.match(regex.pause);
// For each match
// Grab the pause seconds <pause SECONDS>
// Grab the length of the string divided by 2 "string.length/2" between the <pause></pause> tags
// Push the values to "pauses" [seconds, string.length/2]
// Remove the tags from the original string variable
return string;
}
If anyone can explain my how I could do this I would be very thankful! :)
match(/.../g) doesn't save subgroups, you're going to need exec or replace to do that. Here's an example of a replace-based helper function to get all matches:
function matchAll(re, str) {
var matches = [];
str.replace(re, function() {
matches.push([...arguments]);
});
return matches;
}
var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';
var re = /<pause (\d+)>(.+?)<\/pause>/g;
console.log(matchAll(re, string))
Since you're removing tags anyways, you can also use replace directly.
You need to make a loop to find all matched groups of your RegExp pattern in the text.
The matched group is an array containing the original text, the matched value and the match text.
var str = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';
function checkTags(str) {
// Regular expresions we will use
var regex = {
pause: /<pause (.*?)>(.*?)\<\/pause>/g
}
var matches = [];
while(matchedPauses = regex.pause.exec(str)) {
matches.push([matchedPauses[1], matchedPauses[2].length /2]);
};
return matches;
}
console.log(checkTags(str));
As a start point since you have not much so far you could try this one
/<pause [0-9]+>.*<\/pause>/g
Than to get the number out there you match again using
/[0-9]+>/g
To get rid of the last sign >
str = str.slice(0, -1);

How to obtain URL parameter using jquery in case insensitive way

Is there a way to obtain a URL parameter in a case insensitive way using jquery?
Essentially, I'm looking to do something like $.url('?someparameter');, where it would match both http:\\www.test.com?someparameter=ABC or
http:\\www.test.com?SOMEparAMeter=ABC
You should try toLowerCase. This function converts any string to lowercase.
Use a regular expression where you set the case-insensitive flag.
Regular Expressions -- scroll down to "Advanced Searching With Flags"
Please take a look at: How can I get query string values in JavaScript?
The line to adapt to your needs is as follows:
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)", "i");
//"i" for case-insensitive
This doesnt use jQuery, just javascript. But it addresses the question in general.
The problem w/ ucasing the entire ULR is you may be keying off the value to look up an HTML element.
why there is not a collection of keys in URL.searchParams, I do not know, but there is not.
Below is a function i wrote that will find a key and return a value.
I am just barely literate in regEx, so I am sure there is a better regEx that can pull the
value out and omit trailing key value pairs.
function getParm_CI(parm) {
var str = window.location.href;
var rgx = new RegExp('\\b' + parm + '=.*\\b', 'gi');
//this gets an array of matches
var aMatches = str.match(rgx);
if (aMatches == null) return;
var parmVal = aMatches[0].substring(parm.length + 1);
//we shouldnt, but make sure there are not trailing parms
var idx = parmVal.indexOf('&');
//alert('amp:' + idx);
if (idx > -1) parmVal = parmVal.substring(0, idx);
return parmVal;
}
usage would be like this
var topic = getParm_CI('SOMEparAMeter');

Remove special character from the starting of a string and search # symbol.in javascript

I want to remove special characters from the starting of the string only.
i.e, if my string is like {abc#xyz.com then I want to remove the { from the starting. The string shoould look like abc#xyz.com
But if my string is like abc{#xyz.com then I want to retain the same string as it is ie., abc{#xyz.com.
Also I want to check that if my string has # symbol present or not. If it is present then OK else show a message.
The following demonstrates what you specified (or it's close):
var pat = /^[^a-z0-9]*([a-z0-9].*?#.*?$)/i; //pattern for optional non-alphabetic start followed by alphabetic, followed by '#' somewhere
var testString = "{abc#xyz.com"; //Try with {abcxyz.com for alert
arr = pat.exec(testString);
var adjustedString;
if (arr != null) { adjustedString = arr[1]; } //The potentially adjustedString (chopped off non-alphabetic start) will be in capture group 1
else { adjustedString = ""; alert(testString + " does not conform to pattern"); }
adjustedString;
I have used two separate regex objects to achieve what you require .It checks for both the conditions in the string.I know its not very efficient but it will serve your purpose.
var regex = new RegExp(/(^{)/);
var regex1 = new RegExp(/(^[^#]*$)/);
var str = "abc#gmail.com";
if(!regex1.test(str)){
if(regex.test(str))
alert("Bracket found at the beginning")
else
alert("Bracket not found at the beginning")
}
else{
alert("doesnt contain #");
}
Hope this helps

How to get portion of the attribute value using jquery

I have attribute value as:
<div id = "2fComponents-2fPromotion-2f" class = "promotion">
Now I want to get only portion of it, say Promotion and its value 2f, how can I get this using jquery ? Do we have built in function for it ?
You can use a regular expression here:
var attId = $(".promotion").attr("id");
// Perform a match on "Promotion-" followed by 2 characters in the range [0-9a-f]
var match = attId.match(/Promotion-([0-9a-f]{2})/);
alert(match[1]); // match[0] contains "Promotion-2f", match[1] contains "2f"
This assumes that the "value" of Promotion is a hexadecimal value and the characters [a-f] will always be lower case. It's also easily adjusted to match other values, for instance, if I change the regex to /component-([0-9a-f]{2})/, the match array would be ["component-3a", "3a"].
The match method takes a regular expression as its input and searches the string for the results. The result is returned as an array of matches, with the first index being the complete match (equivalent regex for this only would be /Promotion-[0-9a-f]{2}/). Any sub-expression (expressions enclosed in parenthesis) matches are added to the array in the order they appear in the expression, so the (Promotion) part of the expression is added to the array at index 1 and ([0-9a-f]{2}) is added at index 2.
match method on MSDN
var id = $("div.promotion").attr("id");
var index = id.indexOf("Promotion");
var promotion = '';
// if the word 'Promotion' is present
if(index !== -1) {
// extract it up to the end of the string
promotion = id.substring(index);
// split it at the hyphen '-', the second offset is the promotion code
alert(promotion.split('-')[1]);
} else {
alert("promotion code not found");
}
you can get the id attribute like this:
var id= $('div.promotion').attr('id');
But then I think you would have to use regular expressions to parse data from the string, the format doesn't appear to be straight forward.
If you are storing lots of info in the id could you consider using multiple attributes like:
<div class="promotion" zone="3a-2f-2f" home="2f"></div>
Then you could get the data like this:
var zone= $('div.promotion').attr('zone');
var home= $('div.promotion').attr('home');
Or you could use jQuery.data()
HTH
$(function () {
var promotion = $('.promotion').attr('id').match(/Promotion-([0-9a-f]{2})/);
if (promotion.length > 0) {
alert(promotion[1]);
}
else {
return false;
}
});

Categories