Javascript RegEx contains - javascript

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

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(",");

How to find multiple values between two character in a string - JS

I have a string that I am trying to retrieve a value from between two certain characters. I know there are multiple questions like this on here, but I couldn't find one that searches for multiple instances of this scenario in the same string.
Essentially I have a string like this:
'(value one is: 100), (value two is:200)'
and I want to return both 100 and 200. I know that I can write a regex to retrieve content between two characters, but what is the best way to have a function iterate over the string for the : character and grab everything from that until the ) character and only stop when there are no more instances?
Thanks in advance!
For your case, you can use regex to get the numbers from string.
var str = '(value one is: 100), (value two is:200)';
var regex = /\d+/g;
str.match(regex);
Here \d+ will match the numbers from string. g is global flag to match all the elements and not the only first.
Demo: http://jsfiddle.net/tusharj/k96y3evL/
Using Regex
var regex = /\d+/g;
var string = '(value one is: 100), (value two is:200)';
var match = string.match(regex);
alert(match);
Fiddle

JavaScript String test with array of RegEx

I have some doubts regarding RegEx in JavaScript as I am not good in RegEx.
I have a String and I want to compare it against some array of RegEx expressions.
First I tried for one RegEx and it's not working. I want to fix that also.
function check(str){
var regEx = new RegEx("(users)\/[\w|\W]*");
var result = regEx.test(str);
if(result){
//do something
}
}
It is not working properly.
If I pass users, it doesn't match. If I pass users/ or users/somestring, it is matching.
If I change the RegEx to (usersGroupList)[/\w|\W]*, then it is matching for any string that contains the string users
fdgdsfgguserslist/data
I want to match like if string is either users or it should contain users/something or users/
And also I want the string to compare it with similar regex array.
I want to compare the string str with users, users/something, list, list/something, anothermatch, anothermatch/something. If if it matches any of these expression i want to do something.
How can I do that?
Thanks
Then, you'll have to make the last group optional. You do that by capturing the /something part in a group and following it with ? which makes the previous token, here the captured group, optional.
var regEx = new RegExp("(users)(\/[\w|\W]*)?");
What about making:
the last group optional
starting from beginning of the string
Like this:
var regEx = new RegExp("^(users)(\/[\w|\W]*)?");
Same applies for all the others cases, e.g. for list:
var regEx = new RegExp("^(list)(\/[\w|\W]*)?");
All in One Approach
var regEx = new RegExp("^(users|list|anothermatch)(\/[\w|\W]*)?");
Even More Generic
var keyw = ["users", "list", "anothermatch"];
var keyws = keyw.join("|");
var regEx = new RegExp("^("+keyws+")(\/[\w|\W]*)?");
You haven't made the / optional. Try this instead
(users)\/?[\w|\W]*

javascript regexp match tag names

I can't remember the name of it, but I believe you can reference already matched strings within a RegExp object. What I want to do is match all tags within a given string eg
<ul><li>something in the list</li></ul>
the RegExp should be able to match only the same tags, then I will use a recursive function to put all the individual matches in an array. The regex that should work if I can reference the first match would be.
var reg = /(?:<(.*)>(.*)<(?:FIRST_MATCH)\/>)/g;
The matched array should then contain
match[0] = "<ul><li>something in the list</li></ul>";
match[1] = "ul";
match[2] = ""; // no text to match
match[3] = "li";
match[4] = "something in the list";
thanks for any help
It seems like you mean backreference (\1, \2):
var s = '<ul><li>something in the list</li></ul>';
s.match(/<([^>]+)><([^>]+)>(.*?)<\/\2><\/\1>/)
// => ["<ul><li>something in the list</li></ul>",
// "ul",
// "li",
// "something in the list"]
The result is not exactly same with what you want. But point is that the backreference \1, \2 match the string that was matched by earlier group.
It is not possible to parse HTML using regular expressions (if you're interested in the specifics, it is because HTML parsing requires a stronger type of automaton than a finite state automaton which is what a regular expression can express - look up FSA vs FST for more info).
You might be able to get away with some hack for a specific problem, but if you want to reliably parse HTML using Javascript then there are other ways to do this. Search the web for: parse html javascript and you'll get plenty of pointers on how to do this.
I made a dirty workaround. Still needs work thought.
var str = '<div><ul id="list"><li class="something">this is the text</li></ul></div>';
function parseHTMLFromString(str){
var structure = [];
var matches = [];
var reg = /(<(.+)(?:\s([^>]+))*>)(.*)<\/\2>/;
str.replace(reg, function(){
//console.log(arguments);
matches.push(arguments[4]);
structure.push(arguments[1], arguments[4]);
});
while(matches.length){
matches.shift().replace(reg, function(){
console.log(arguments);
structure.pop();
structure.push(arguments[1], arguments[4]);
matches.push(arguments[4]);
});
}
return structure;
}
// parseHTMLFromString(str); // ["<div>", "<ul id="list">", "<li class="something">", "this is the text"]

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

Categories

Resources