Matching and returning a regex between two values - javascript

I am trying to get the values from a string using regex, the value is that of the text between tt=" and "&
So, for example, "tt="Value"&" I would only want to get the word "Value" out of this.
So far I have this: /tt=.*&/ which gives me "tt=Value"&, Then, to get the value I am thinking to split the match on = and remove the 2 characters from the end. I feel though, that this would be an awful way to do this and would like to see if it could be done in the regex?

You're on the right track for matching the entire context inside of the string, but you want to use a capturing group to match/capture the value between the quotes instead of splitting on = and having to remove the two quote chars.
var r = 'tt="Value"&'.match(/tt="([^"]*)"/)[1];
if (r)
console.log(r); //=> "Value"

I know this isn't really the answer you are looking for since it doesn't involve regex but it's the way I usually do it.
strvariable = strvariable.Remove(0,strvariable.IndexOf("=") + 2);
strvariable = strvariable.Remove(strvariable.IndexOf("\""), strvariable.Length - strvariable.IndexOf("\""));
this would give you the result you were looking for which is Value in this instance.

Related

Use only one of the characters in regular expression javascript

I guess that should be smth very easy, but I'm stuck with that for at least 2 hours and I think it's better to ask the question here.
So, I've got a reg expression /&t=(\d*)$/g and it works fine while it is not ?t instead of &t in url. I've tried different combinations like /\?|&t=(\d*)$/g ; /\?t=(\d*)$|/&t=(\d*)$/g ; /(&|\?)t=(\d*)$/g and various others. But haven't got the expected result which is /\?t=(\d*)$/g or /&t=(\d*)$/g url part (whatever is placed to input).
Thx for response. I think need to put some details here. I'm actually working on this peace of code
var formValue = $.trim($("#v").val());
var formValueTime = /&t=(\d*)$/g.exec(formValue);
if (formValueTime && formValueTime.length > 1) {
formValueTime = parseInt(formValueTime[1], 10);
formValue = formValue.replace(/&t=\d*$/g, "");
}
and I want to get the t value whether reference passed with &t or ?t in references like youtu.be/hTWKbfoikeg?t=82 or similar one youtu.be/hTWKbfoikeg&t=82
To replace, you may use
var formValue = "some?some=more&t=1234"; // $.trim($("#v").val());
var formValueTime;
formValue = formValue.replace(/[&?]t=(\d*)$/g, function($0,$1) {
formValueTime = parseInt($1,10);
return '';
});
console.log(formValueTime, formValue);
To grab the value, you may use
/[?&]t=(\d*)$/g.exec(formValue);
Pattern details
[?&] - a character class matching ? or &
t= - t= substring
(\d*) - Group 1 matching zero or more digits
$ - end of string
/\?t=(\d*)|\&t=(\d*)$/g
you inverted the escape character for the second RegEx.
http://regexr.com/3gcnu
I want to thank you all guys for trying to help. Special thanks to #Wiktor Stribiżew who gave the closest answer.
Now the piece of code I needed looks exactly like this:
/[?&]t=(\d*)$/g.exec(formValue);
So that's the [?&] part that solved the problem.
I use array later, so /\?t=(\d*)|\&t=(\d*)$/g doesn't help because I get an array like [t&=50,,50] when reference is & type and the correct answer [t?=50,50] when reference is ? type just because of the order of statements in RegExp.
Now, if you're looking for a piece of RegExp that picks either character in one place while the rest of RegExp remains the same you may use smth like this [?&] for the example where wanted characters are ? and &.

Javascript RegExp matching returning too many

I need to take a string and get some values from it. I have this string:
'tab/tab2/tab3'
The '/tab3' is optional so this string should also work:
'tab/tab2'
I currently am trying this which works for the most part:
'tab/tab2/tab3'.match(new RegExp('^tab/([%a-zA-Z0-9\-\_\s,]+)(/([%a-zA-Z0-9-_s,]+)?)$'));
This will return:
["tab/tab2/tab3", "tab2", "/tab3", "tab3"]
but I want it to return
["tab/tab2/tab3", "tab2", "tab3"]
So I need to get rid of the 3rd index item ("/tab3") and also get it to work with just the 'tab/tab2' string.
To complicate it even more, I only have control over the /([%a-zA-Z0-9-_s,]+)? part in the last grouping meaning it will always wrap in a grouping.
you don't need regex for this, just use split() method:
var str = 'tab/tab2/tab3';
var arr = str.split('/');
console.log(arr[0]); //tab
console.log(arr[1]); //tab2
jsfiddle
I used this regexp to do this:
'tab/tab2/tab3'.match(new RegExp('^tab/([%a-zA-Z0-9\-\_\s,]+)(?:/)([%a-zA-Z0-9-_s,]+)$'));
Now I get this return
["tab/tab2/tab3", "tab2", "tab3"]
Now I just need to allow 'tab/tab2' to be accepted aswell...
Do not put regex between " or ', using /g to make global search else only first occurrence is returned
"tab/tab2/tab3".match(/tab[0-9]/g)

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

javascript regex to extract the first character after the last specified character

I am trying to extract the first character after the last underscore in a string with an unknown number of '_' in the string but in my case there will always be one, because I added it in another step of the process.
What I tried is this. I also tried the regex by itself to extract from the name, but my result was empty.
var s = "XXXX-XXXX_XX_DigitalF.pdf"
var string = match(/[^_]*$/)[1]
string.charAt(0)
So the final desired result is 'D'. If the RegEx can only get me what is behind the last '_' that is fine because I know I can use the charAt like currently shown. However, if the regex can do the whole thing, even better.
If you know there will always be at least one underscore you can do this:
var s = "XXXX-XXXX_XX_DigitalF.pdf"
var firstCharAfterUnderscore = s.charAt(s.lastIndexOf("_") + 1);
// OR, with regex
var firstCharAfterUnderscore = s.match(/_([^_])[^_]*$/)[1]
With the regex, you can extract just the one letter by using parentheses to capture that part of the match. But I think the .lastIndexOf() version is easier to read.
Either way if there's a possibility of no underscores in the input you'd need to add some additional logic.

regex search a string for contents between two strings

I am trying my upmost best to get my head around regex, however not having too much luck.
I am trying to search within a string for text, I know how the string starts, and i know how the string ends, I want to return ALL the text inbetween the string including the start and end.
Start search = [{"lx":
End search = }]
i.e
[{"lx":variablehere}]
So far I have tried
/^\[\{"lx":(*?)\}\]/;
and
/(\[\{"lx":)(*)(\}\])/;
But to no real avail... can anyone assist?
Many thanks
You're probably making the mistake of believing the * is a wildcard. Use the period (.) instead and you'll be fine.
Also, are you sure you want to stipulate zero or more? If there must be a value, use + (one or more).
Javascript:
'[{"lx":variablehere}]'.match(/^\[\{"lx":(.+?)\}\]/);
The * star character multiplies the preceding character. In your case there's no such character. You should either put ., which means "any character", or something more specific like \S, which means "any non whitespace character".
Possible solution:
var s = '[{"lx":variablehere}]';
var r = /\[\{"(.*?)":(.*?)\}\]/;
var m = s.match(r);
console.log(m);
Results to this array:
[ '[{"lx":variablehere}]',
'lx',
'variablehere',
index: 0,
input: '[{"lx":variablehere}]' ]
\[\{"lx"\:(.*)\}\]
This should work for you. You can reach the captured variable by \1 notation.
Try this:
^\[\{\"lx\"\:(.*)\}\]$
all text between [{"lx": and }] you will find in backreference variable (something like \$1 , depends on programming language).

Categories

Resources