How can i get value with javascript regular expressions - javascript

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")

Related

Extract Twitter handlers from string using regex in JavaScript

I Would like to extract the Twitter handler names from a text string, using a regex. I believe I am almost there, except for the ">" that I am including in my output. How can I change my regex to be better, and drop the ">" from my output?
Here is an example of a text string value:
"PlaymakersZA, Absa, DiepslootMTB"
The desired output would be an array consisting of the following:
PlaymakersZA, Absa, DiepslootMTB
Here is an example of my regex:
var array = str.match(/>[a-z-_]+/ig)
Thank you!
You can use match groups in your regex to indicate the part you wish to extract.
I set up this JSFiddle to demonstrate.
Basically, you surround the part of the regex that you want to extract in parenthesis: />([a-z-_]+)/ig, save it as an object, and execute .exec() as long as there are still values. Using index 1 from the resulting array, you can find the first match group's result. Index 0 is the whole regex, and next indices would be subsequent match groups, if available.
var str = "PlaymakersZA, Absa, DiepslootMTB";
var regex = />([a-z-_]+)/ig
var array = regex.exec(str);
while (array != null) {
alert(array[1]);
array = regex.exec(str);
}
You could just strip all the HTML
var str = "PlaymakersZA, Absa, DiepslootMTB";
$handlers = str.replace(/<[^>]*>|\s/g,'').split(",");

Javascript Regular Expression (x)

I have a piece of code as follows:
var str = "foo xxx eee dsds";
var regex = /(foo)/;
console.log(str.match(regex));
I expected output is:
foo
But the actual output is:
foo, foo
If i declare:
var regex = /(foo)/g;
The output only is foo
Can anyone help me? Thank for your help.
The second value in the array is the captured value, in absence of global modifiers match results contains the captured values. If you are removed the capturing group the result will only contains the match.
var str = "foo xxx eee dsds";
console.log(str.match(/(foo)/));
console.log(str.match(/(foo)/g));
console.log(str.match(/foo/));
Check MDN documentation :
If the regular expression does not include the g flag, returns the same result as RegExp.exec(). The returned Array has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.
If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.
Your output is a return value of the match method which is an array. To get the desired output, use either str.match(regex)[0] (the whole matched string) or str.match(regex)[1] (the captured substring matching (foo) which is the same in your case). But it's better to save the match array first and check if it is null or not (if the string doesn't match, it is null and null[0] will cause an error):
var match = str.match(regex);
if(match)
console.log(match[0]);
else
// do whatever you want when there's no match

Extract Fractional Number From String

I have a string that looks something like this
Hey this is my 1.20 string
I'm trying to just extract 1.20 from it.
What's the best way to do this?
I've tried something like this, but I get the value of 1.20,20 rather than just 1.20
var query = $(".query_time").html();
var matches = query.match(/\d.(\d+)/);
The result of the match function is an array, not a string. So simply take
var nb = query.match(/\d.(\d+)/)[0];
BTW, you should also escape the dot if you want to have more precise match :
var nb = query.match(/\d\.(\d+)/)[0];
or this if you want to accept commas (depends on the language) :
var nb = query.match(/\d[\.,](\d+)/)[0];
But the exact regex will be based on your exact needs, of course and to match any number (scientific notation ?) I'd suggest to have a look at more complex regex.
The value of matches is actually [ "1.20", "20" ] (which is an array). If you print it, it will get converted to a string, hence the 1.20,20.
String.match returns null or an array of matches where the first index is the fully matched part and then whichever parts you wanted. So the value you want is matches[0].
Try the following
var nb = query.match(/\d\.\d+/)[0]; // "1.20"
You need to escape . because that stands for any character.
Remove the capture group (\d+) and the second match is not returned
Add [0] index to retrieve the match

Regex to extract substring, returning 2 results for some reason

I need to do a lot of regex things in javascript but am having some issues with the syntax and I can't seem to find a definitive resource on this.. for some reason when I do:
var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test)
it shows
"afskfsd33j, fskfsd33"
I'm not sure why its giving this output of original and the matched string, I am wondering how I can get it to just give the match (essentially extracting the part I want from the original string)
Thanks for any advice
match returns an array.
The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:
var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);
Each group defined by parenthesis () is captured during processing and each captured group content is pushed into result array in same order as groups within pattern starts. See more on http://www.regular-expressions.info/brackets.html and http://www.regular-expressions.info/refcapture.html (choose right language to see supported features)
var source = "afskfsd33j"
var result = source.match(/a(.*)j/);
result: ["afskfsd33j", "fskfsd33"]
The reason why you received this exact result is following:
First value in array is the first found string which confirms the entire pattern. So it should definitely start with "a" followed by any number of any characters and ends with first "j" char after starting "a".
Second value in array is captured group defined by parenthesis. In your case group contain entire pattern match without content defined outside parenthesis, so exactly "fskfsd33".
If you want to get rid of second value in array you may define pattern like this:
/a(?:.*)j/
where "?:" means that group of chars which match the content in parenthesis will not be part of resulting array.
Other options might be in this simple case to write pattern without any group because it is not necessary to use group at all:
/a.*j/
If you want to just check whether source text matches the pattern and does not care about which text it found than you may try:
var result = /a.*j/.test(source);
The result should return then only true|false values. For more info see http://www.javascriptkit.com/javatutors/re3.shtml
I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.
Just get rid of the parenthesis and that will give you an array with one element and:
Change this line
var test = tesst.match(/a(.*)j/);
To this
var test = tesst.match(/a.*j/);
If you add parenthesis the match() function will find two match for you one for whole expression and one for the expression inside the parenthesis
Also according to developer.mozilla.org docs :
If you only want the first match found, you might want to use
RegExp.exec() instead.
You can use the below code:
RegExp(/a.*j/).exec("afskfsd33j")
I've just had the same problem.
You only get the text twice in your result if you include a match group (in brackets) and the 'g' (global) modifier.
The first item always is the first result, normally OK when using match(reg) on a short string, however when using a construct like:
while ((result = reg.exec(string)) !== null){
console.log(result);
}
the results are a little different.
Try the following code:
var regEx = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
var result = sample_string.match(regEx);
console.log(JSON.stringify(result));
// ["1 cat","2 fish"]
var reg = new RegExp('[0-9]+ (cat|fish)','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null) {
console.dir(JSON.stringify(result))
};
// '["1 cat","cat"]'
// '["2 fish","fish"]'
var reg = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null){
console.dir(JSON.stringify(result))
};
// '["1 cat","1 cat","cat"]'
// '["2 fish","2 fish","fish"]'
(tested on recent V8 - Chrome, Node.js)
The best answer is currently a comment which I can't upvote, so credit to #Mic.

assign matched values from jquery regex match to string variable

I am doing it wrong. I know.
I want to assign the matched text that is the result of a regex to a string var.
basically the regex is supposed to pull out anything in between two colons
so blah:xx:blahdeeblah
would result in xx
var matchedString= $(current).match('[^.:]+):(.*?):([^.:]+');
alert(matchedString);
I am looking to get this to put the xx in my matchedString variable.
I checked the jquery docs and they say that match should return an array. (string char array?)
When I run this nothing happens, No errors in the console but I tested the regex and it works outside of js. I am starting to think I am just doing the regex wrong or I am completely not getting how the match function works altogether
I checked the jquery docs and they say that match should return an array.
No such method exists for jQuery. match is a standard javascript method of a string. So using your example, this might be
var str = "blah:xx:blahdeeblah";
var matchedString = str.match(/([^.:]+):(.*?):([^.:]+)/);
alert(matchedString[2]);
// -> "xx"
However, you really don't need a regular expression for this. You can use another string method, split() to divide the string into an array of strings using a separator:
var str = "blah:xx:blahdeeblah";
var matchedString = str.split(":"); // split on the : character
alert(matchedString[1]);
// -> "xx"
String.match
String.split

Categories

Resources