I want check phone numbers. Right format is 38xxxxxxxxxx.
My check:
var phoneNumber=document.getElementById('phone').value;
var re=new RegExp("^[38]\d{10}$");
var res=phoneNumber.match(re);
I always get null. What's wrong?
When using the RegExp constructor function with quotes, normal string escape rules apply. Thus, you need to escape the special character \d as \\d. Also you need to change [38] to simply 38, as [38] matches 3 or 8.
var str = '381234567890';
var re = new RegExp("^38\\d{10}$");
// or new RegExp(/^38\d{10}$/); without quotes
// or re = /^38\d{10}$/;
var res = str.match(re);
document.body.innerHTML = "Match result: " + res;
var res=phoneNumber.match(/38[0-9]{8,10}/m);
phone number length allowed :10-12
Your regex is wrong, if you want to match 38xxxxxxxxxx you should remove [] brackets because this means 3 or 8 and afterwards it tries to match 10 digits, so just remove the []
var re=new RegExp("^38\d{10}$");
When using the constructor function, the normal string escape rules are necessary.
new RegExp("^38\\d{10}$");
Related
I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)
Say, I have a text stored as:
var val1 = 'l-oreal';
I want to match val1 such that, it reads val1 and ignores hyphen (dash) in it. I want a regex that ignores special characters in a text. Is that possible?
I don't want to remove special character from the text. I want to ignore it.
You can match against the regex /[a-z]+/gi and then join by a space or any other character:
var testString = "any string l-orem";
var matcher = /[a-z]+/gi;
var matches = testString.match(matcher);
var result = matches.join('');
console.log(result);
This, of course, doesn't change your original string, and can be simply customized to your own needs.
You can either use ^ in order to select your special characters then replace it to an empty string '', as:
val1.replace(/([^a-zA-z0-9]+)/g, s0 => ''); // loreal
All except a-zA-Z-0-9 will be removed.
Updated post for scenario when:
The string must contain characters abc and ignore any special
characters
for this approach, you could make use of match to know if your string has any matches on your regex. If so, then you could use replace to switch special chars to empty string:
function strChecker(str) {
var response;
if(val1.match(/lorem/)) {
response = val1.replace(/([^a-zA-z0-9]+)/g, s0 => '');
}
return response;
}
strChecker('ha-ha?lorem') // returns hahalorem
strChecker('ha-ha?loram') // return undefined
var val1 = 'l-oreal';
var val2 = val1.replace(/\W/g,''); // remove any non-alphanumerics
console.log(val1); // still the same, not changed
console.log(val2); // only alphanumerics
var str = "^" + "/post/\d+" + "$";
var regex = new RegExp(str);
var flag = regex.test("/post/3333");
console.log(flag) // -> false
console.log(regex) // -> /^\/post\/d+$/
I'm expecting the result becomes true, but it results in false.
I think the problem is "\" is added automatically before "/" when RegExp instance is created.
How am I supposed to write in order to make it work?
You don't need the new RegExp constructor and string
Here example
var regex = /post\/\d+$/;
var flag = regex.test("/post/3333");
I removed ^ flag, because regex will not work with this format of input "website/post/3333"
Here's a more specific regular expression to match the format of /post/####:
var regex = /\/post\/[0-9]+$/;
var flag = regex.test("/post/3333");
This will test for the string /post/ followed by one or more digits, occurring at the end of the line.
Likewise:
var regex = /\/post\/[0-9]{4}$/;
var flag = regex.test("/post/3333");
will test for the string /post/ followed by 4 digits, occurring at the end of the line.
I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.
I'm new to using regexp, can someone give me the regexp that will strip out everything but an integer from a string in javascript?
I would like to take the string "http://www.foo.com/something/1234/somethingelse" and get it down to 1234 as an integer.
Thanks
var str = "something 123 foo 432";
// Replace all non-digits:
str = str.replace(/\D/g, '');
alert(str); // alerts "123432"
In response to your edited question, extracting a string of digits from a string can be simple, depending on whether you want to target a specific area of the string or if you simply want to extract the first-occurring string of digits. Try this:
var url = "http://www.foo.com/something/1234/somethingelse";
var digitMatch = url.match(/\d+/); // matches one or more digits
alert(digitMatch[0]); // alerts "1234"
// or:
var url = "http://x/y/1234/z/456/v/890";
var digitMatch = url.match(/\d+/g); // matches one or more digits [global search]
digitMatch; // => ['1234', '456', '890']
This is just for integers:
[0-9]+
The + means match 1 or more, and the [0-9] means match any character from the range 0 to 9.
uri = "http://www.foo.com/something/1234/somethingelse";
alert(uri.replace(/.+?\/(\d+)\/.+/, "$1"))
Just define a character-class that requires the values to be numbers.
/[^0-9]/g // matches anything that is NOT 0-9 (only numbers will remain)