Regex to extract two digits from phone number - javascript

I am trying to take only 2 characters from my phone no.
I have used regex match ^\+55 and this will return the following example.
Phone No : +5546342543
Result : 46342543
Expected Result was only 46.
I don't want to use substring for the answer instead I want to extract that from the phone no with regex.
Can anybody help me on this.
Thank you.

The pattern you used - ^\+55 - matches a literal + in the beginning of the string and two 5s right after.
46 is the substring that appears right after the initial +55. In some languages, you can use a look-behind (see example) to match some text preceded with another.
JavaScript has no look-behind support, so, you need to resort to capturing groups.
You can use string#match or RegExp#exec to obtain that captured text marked with round brackets:
var s = '+5546342543';
if ((m=/^\+55(\d{2})/.exec(s)) !== null) {
document.write(m[1]);
}
This example handles the case when you get no match.

Just try with:
'+5546342543'.match(/^\+55(\d{2})/)[1];

This will get what you want
"+5546342543".match(/^\+55(.*)/)[1]

This solves your problem ?
phoneNumber = "+5546342543"
phone = phoneNumber.substr(3) // returns "46342543"
twoDigits = phoneNumber.substr(3,2) // returns "46"
Using the substr() method as quoted :
The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.
Syntax: str.substr(start[, length])
Source : Mozilla MDN

Related

regex replace with groups plus optional group in javascript

What's working: I'm using a regex similar to the one below for phone numbers (the actual regex is here) that can grab extensions
as an optional 4th group. The regex itself is working fine for the
first three groups as shown below
"555-555-5555 x214".replace(/([\d]{3})-([\d]{3})-([\d]{4})(?: +x([\d]+))?/, "$1-$2-$3");
// returns 555-555-5555
What I'm looking for: I can't find the syntax for the replace string to insert the phone extension preceded by a x ONLY if the 4th group is
captured. In my real regex, the phone extension could be marked by
few different character designations which I would like to simply replace
with an "x".
If I use:
"555-555-5555 x214".replace(/([\d]{3})-([\d]{3})-([\d]{4})(?: +x([\d]+))?/, "$1-$2-$3 x4");
// returns 555-555-5555 x214
"555-555-5555".replace(/([\d]{3})-([\d]{3})-([\d]{4})(?: +x([\d]+))?/, "$1-$2-$3 x4");
// will return 555-555-5555 x
In the last example, I get the "x" (which I'm not surprised by), so I'm looking for the syntax to only add the "x" plus group 4 if something was captured.
Is this possible with String.replace? If not, is there a more efficient way to replace these groups with a formatted number type once I've identified their parts?
The String#replace function can also take a function as a 2nd argument, which can be more expressive that a string.
For example:
"555-555-5555".replace(/(\d{3})-(\d{3})-(\d{4})(?: +x(\d+))?/, replacer);
function replacer(match, p1, p2, p3, p4, offset, string) {
return `${p1}-${p2}-${p3}` + (p4 ? ` x${p4}` : '')
}
See MDN documentation for more details :)
Note that your regex needed some modifications. Play with it here: https://regex101.com/r/rtJYTw/1

Add a space to UK Postcode in correct place Javascript

I am trying to write a basic function that will allow me to add a space to UK postcodes where the spaces have been removed.
UK postcodes always have a space before the final digit of the postcode string.
Some examples with no spacing and with correct spacing:
CB30QB => CB3 0QB
N12NL => N1 2NL
OX144FB => OX14 4FB
To find the final digit in the string I am regex /\d(?=\D*$)/g and the Javascript I have in place currently is as follows:
// Set the Postcode
var postCode = "OX144FB";
// Find the index position of the final digit in the string (in this case '4')
var postcodeIndex = postCode.indexOf(postCode.match(/\d(?=\D*$)/g));
// Slice the final postcode at the index point, add a space and join back together.
var finalPostcode = [postCode.slice(0, postcodeIndex), ' ', postCode.slice(postcodeIndex)].join('');
return finalPostcode;
I am getting the following results when I change the set postcost:
CB30QB becomes CB3 0QB - Correct
N12NL becomes N1 2NL - Correct
CB249LQ becomes CB24 9LQ - Correct
OX144FB becomes OX1 44FB - Incorrect
OX145FB becomes OX14 5FB - Correct
It seems that the issue might be to do with having two digits of the same value as most other combinations seem to work.
Does anyone know how I can fix this?
I should use string.replace
string.replace(/^(.*)(\d)/, "$1 $2");
DEMO
You can use replace() with regex, you need to place space before 3 letters from the end
document.write('CB30QB'.replace(/^(.*)(.{3})$/,'$1 $2')+'<br>');
document.write('N12NL'.replace(/^(.*)(.{3})$/,'$1 $2')+'<br>');
document.write('CB249LQ'.replace(/^(.*)(.{3})$/,'$1 $2')+'<br>');
document.write('OX144FB'.replace(/^(.*)(.{3})$/,'$1 $2'));
As everyone else is answering, .replace() is easier. However, let me point what's wrong in the code.
The problem is you're using postCode.indexOf() to find the first occurence of what has been matched. In this case:
Text: OX144FB
Match: ^ match is correct: "4"
Text: OX144FB
IndexOf: ^ first occurence of "4"
To fix it, use the .index of the match object:
// Find the index position of the final digit in the string (in this case '4')
var postcodeIndex = postCode.match(/\d(?=\D*$)/g).index;
var postCode = "OX144FB";
return postCode.replace(/^(.*)(\d)(.*)/, "$1 $2$3");
Using the String.prototype.replace method is obviously the easiest way:
return postCode.replace(/(?=\d\D*$)/, ' ');
or using the greediness:
return postCode.replace(/^(.*)(?=\d)/, '$1 ');
Your previous code doesn't work because you are searching with indexOf the substring matched with the String.prototype.match() method (that is the last digit before the end). But if this digit is several times in the string, indexOf will return the position of the first occurrence.
As an aside, when you want to find the position of a match in a string, use the String.prototype.search() method that returns this position.
This is an old problem, but whilst Avinash Raj's solution works, it only works if all your postcodes are without spaces. If you have a mix, and you want to regularize them to having a single space, you can use this regex:
string.replace(/(\S*)\s*(\d)/, "$1 $2");
DEMO - it even works with more than one space!

Regular expression matching URL parameters

Given the following two strings
?room=any_characters123&name=John
?room=any_characters123
I want to extract "any_characters123" using regular expression.
I've tried
(?<=room=)(\w)+(?=\&)
but this one fails on the second string (because the matched string must end with "&").
How can I edit my regular expression so that it matches any_characters123 in both strings?
Since javascript won't support lookbehinds, you need to use capturing group.
\?room=(\w+)
Example:
> var s = "?room=any_characters123&name=John"
> var s1 = "?room=any_characters123"
undefined
> var re = /\?room=(\w+)/;
undefined
> console.log(re.exec(s)[1])
any_characters123
undefined
> console.log(re.exec(s1)[1])
any_characters123
If you're using JS, lookbehind is not supported. You can modify the regex as follows:
room=([^&]+)
Try putting * in the end of your expression:
room=(\w+)\&*?
It will test for zero or plus ocurrences of &
This should do the trick:
/room=(\w+)&?/
/*
find "room=" then match any word characters (at least one) until you
possibly hit "&"
*/
Example:
/room=(\w+)&?/.test("?room=any_characters123")
// => true
"?room=any_characters123".match(/room=(\w+)&?/)
// => ["room=any_characters123", "any_characters123"]
Run the string through two regex tests, the one you already have, and then this one:
(?<=room=)(\w){1,}$

RegEx - Get All Characters After Last Slash in URL

I'm working with a Google API that returns IDs in the below format, which I've saved as a string. How can I write a Regular Expression in javascript to trim the string to only the characters after the last slash in the URL.
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'
Don't write a regex! This is trivial to do with string functions instead:
var final = id.substr(id.lastIndexOf('/') + 1);
It's even easier if you know that the final part will always be 16 characters:
var final = id.substr(-16);
A slightly different regex approach:
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
Breaking down this regex:
\/ match a slash
( start of a captured group within the match
[^\/] match a non-slash character
+ match one of more of the non-slash characters
) end of the captured group
\/? allow one optional / at the end of the string
$ match to the end of the string
The [1] then retrieves the first captured group within the match
Working snippet:
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9';
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
// display result
document.write(afterSlashChars);
Just in case someone else comes across this thread and is looking for a simple JS solution:
id.split('/').pop(-1)
this is easy to understand (?!.*/).+
let me explain:
first, lets match everything that has a slash at the end, ok?
that's the part we don't want
.*/ matches everything until the last slash
then, we make a "Negative lookahead" (?!) to say "I don't want this, discard it"
(?!.*) this is "Negative lookahead"
Now we can happily take whatever is next to what we don't want with this
.+
YOU MAY NEED TO ESCAPE THE / SO IT BECOMES:
(?!.*\/).+
this regexp: [^\/]+$ - works like a champ:
var id = ".../base/nabb80191e23b7d9"
result = id.match(/[^\/]+$/)[0];
// results -> "nabb80191e23b7d9"
This should work:
last = id.match(/\/([^/]*)$/)[1];
//=> nabb80191e23b7d9
Don't know JS, using others examples (and a guess) -
id = id.match(/[^\/]*$/); // [0] optional ?
Why not use replace?
"http://google.com/aaa".replace(/(.*\/)*/,"")
yields "aaa"

Extracting numbers from a string using regular expressions

I am clueless about regular expressions, but I know that they're the right tool for what I'm trying to do here: I'm trying to extract a numerical value from a string like this one:
approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^
Ideally, I'd extract the following from it: 12345678901234567890123456789012 None of the regexes I've tried have worked. How can I get the value I want from this string?
This will get all the numbers:
var myValue = /\d+/.exec(myString)
mystr.match(/assignment_group=([^\^]+)/)[1]; //=> "12345678901234567890123456789012"
This will find everything from the end of "assignment_group=" up to the next caret ^ symbol.
Try something like this:
/\^assignment_group=(\d*)\^/
This will get the number for assignment_group.
var str = 'approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^',
regex = /\^assignment_group=(\d*)\^/,
matches = str.match(regex),
id = matches !== null ? matches[1] : '';
console.log(id);
If there is no chance of there being numbers anywhere but when you need them, you could just do:
\d+
the \d matches digits, and the + says "match any number of whatever this follows"

Categories