what regular expression would I use to retrieve the digits that follow this string? - javascript

I'm using jQuery to retrieve the class attribute and I need to get the a substring of the digits that follow the substring "position"
for example
"position7 selected" I need to retrieve "7"
for example
"navitem position14 selected" I need to retrieve "14"
I started writing:
$(this).attr('class').match(/(\d+)$/))
But I am getting lost with the regular expression, any help much appreciated.
I actually really really like regular expressions but I'm still learning!
update due to first answer: there might be another group of digits which I need to ignore
For example "navitem2 position14 selected" I need to retrieve "14"

"navitem position14 selected".match(/position(\d+)/)[1]
The call returns ["position14", "14"], so the [1] element is 14.
You're on the right track with the (\d+), it will match a contiguous group of digits. This just says only match that group when it directly follows the literal string "position".

Your attempt has two problems. The first is you anchor it to the end of the string with $. So instead of giving you the digits after position it will give you digits at the endof the string. At the same time you don't mention position at all. What you are looking for is this:
var matches = str.match(/position(\d+)/);
Now matches will be
["position14", "14"]

You can replace everything that is not a number
str.replace(/\D/g,"");
If other numbers are present in the string you can still use replace
str.replace(/^.*position(\d+).*$/,"$1");
However, you may want to go for one of the other regex expressions in the other answers.

var r = "aaa 1 bb 2 position 113 dd".match(/position\s*(\d+)/)
if (r instanceof Array )
return r.pop()

Related

how to find comma or other symbols in a string using javascript?

Let's assume I have an string... I want to convert them to numbers.. and It will only work for alphabets...
if my string contains comma or dot... I would like to avoid it...
I'm working with words by word. so if the string is--
"Hi, let's play!"
it should be converted to--
"4510, 584578'52 69775246!"
how can I do it?
function hasNumber(gottenWord) {
return (/\d/.test(gottenWord));
}
const numberTrue = hasNumber(gottenWord);
I was able to search for numbers but not sure how to search for symbols.. and I even have some custom symbols to search.
If all you want is to avoid anything that's not in abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ then the easiest way is to change \d to [^a-zA-Z]. [] indicates a character set, and starting a set with ^ means "not these".

Matching and returning a regex between two values

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.

Extract specific chars from a string using a regex

I need to split an email address and take out the first character and the first character after the '#'
I can do this as follows:
'bar#foo'.split('#').map(function(a){ return a.charAt(0); }).join('')
--> bf
Now I was wondering if it can be done using a regex match, something like this
'bar#foo'.match(/^(\w).*?#(\w)/).join('')
--> bar#fbf
Not really what I want, but I'm sure I miss something here! Any suggestions ?
Why use a regex for this? just use indexOf to get the char at any given position:
var addr = 'foo#bar';
console.log(addr[0], addr[addr.indexOf('#')+1])
To ensure your code works on all browsers, you might want to use charAt instead of []:
console.log(addr.charAt(0), addr.charAt(addr.indexOf('#')+1));
Either way, It'll work just fine, and This is undeniably the fastest approach
If you are going to persist, and choose a regex, then you should realize that the match method returns an array containing 3 strings, in your case:
/^(\w).*?#(\w)/
["the whole match",//start of string + first char + .*?# + first string after #
"groupw 1 \w",//first char
"group 2 \w"//first char after #
]
So addr.match(/^(\w).*?#(\w)/).slice(1).join('') is probably what you want.
If I understand correctly, you are quite close. Just don't join everything returned by match because the first element is the entire matched string.
'bar#foo'.match(/^(\w).*?#(\w)/).splice(1).join('')
--> bf
Using regex:
matched="",
'abc#xyz'.replace(/(?:^|#)(\w)/g, function($0, $1) { matched += $1; return $0; });
console.log(matched);
// ax
The regex match function returns an array of all matches, where the first one is the 'full text' of the match, followed by every sub-group. In your case, it returns this:
bar#f
b
f
To get rid of the first item (the full match), use slice:
'bar#foo'.match(/^(\w).*?#(\w)/).slice(1).join('\r')
Use String.prototype.replace with regular expression:
'bar#foo'.replace(/^(\w).*#(\w).*$/, '$1$2'); // "bf"
Or using RegEx
^([a-zA-Z0-9])[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#([a-zA-Z0-9-])[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$
Fiddle

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