so I am looking to get an specific numerical value using Javascript and regular expressions from a string like this: *#13**67*value##
So from
*#13**67*2##
*#13**67*124##
*#13**67*1##
I need to get 2, 124 and 1. Any help will be really appreciated. Thanks!
If your strings are always in this format, match the digits at the end of the string.
var r = '*#13**67*124##'.match(/\d+(?=#+$)/);
if (r)
console.log(r[0]); // => "124"
Multi-line matching:
var s = '*#13**67*2##\n*#13**67*124##\n*#13**67*1##',
r = s.match(/\d+(?=#+$)/gm)
console.log(r); // => [ '2', '124', '1' ]
Perhaps splitting the string?
var r = '*#13**67*124##'.split(/[*#]+/).filter(Boolean).pop()
console.log(r); // => "124"
function getValue(string) {
return parseInt(string.replace(/^.*(\d+)##$/gi, "$1"), 10);
}
This is a nice example for use regex lookahead.
You can use this regex:
\d+(?=##)
Working demo
How about this:
var regex = /^\*\#\d{2}\*{2}\d{2}\*(\d+)\#{2}$/;
var value = '*#13**67*124##'.match(regex)[1]; // value will be 124
Related
My sample code :
let str = 'myname:is:gopal#gmail.com';
console.log(str.match(":" + "(.*)" + "#")[1]));
returns for above regex => is:gopal // returned value
expected output is => gopal // i want only *gopal*
Note: all the strings are dynamic, except : and # these special characters.
Thanks in advance.
Positive Lookahead and Positive Lookbehind can solve your problem.
UPD: match non-word characters (by #toto)
s = 'myname:is:gopal#gmail.com'
s.match(/(?<=:)[^:]+(?=#)/)
// --> ["gopal", index: 10, input: "myname:is:gopal#gmail.com", groups: undefined]
regex101 test here
Many thanks #Mandy8055
let str = "myname:is:gopal#gmail.com";
console.log(str.match('.*:(.*)#.*')[1]); // returns gopal
i'm trying to split a String which contains an Uppercase Part + a Lowercase Part in Javascript (ES5). The String always looks like "UPPERlower".
Here's what i currently use
"ABCabc".match(/^[A-Z]+/g).concat("ABCabc".match(/[a-z]+$/g)) //result is ["ABC", "abc"]
Is there a cleaner code to achieve this?
EDIT:
Ori Drori's answer and mplungjan's answer are both correct for my Problem.
You can use | to match either the uppercase or lowercase sequence:
var result = "ABCabc".match(/[A-Z]+|[a-z]+/g)
console.log(result);
Destructuring is the modern way
const s="UPPERlower";
let [,upper, lower] =/([A-Z]+)([a-z]+)/g.exec(s);
console.log(upper,lower);
Looping - NOTE: What is the difference between RegExp’s exec() function and String’s match() function?
const s = "UPPERlower UPlow 123 lowUP UPPlowe";
// Note:above will produce low UP using .match(/[A-Z]+|[a-z]+/g) instead of capturing
const re = /([A-Z]+)([a-z]+)/g;
while (match = re.exec(s)) {
[, upper, lower] = match;
console.log(upper, lower)
}
Older way:
var parts=/([A-Z]+)([a-z]+)/g.exec("UPPERlower");
console.log(parts[1],parts[2]);
Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);
I have the following string:
"4/7/12"
and I would like to replace each number with this formula:
(25 - x) where 'x' is the number from the string.
For example:
"4/7/12" would be translated into: "21/18/13"
How can I do this using 'replace()' and Regex ??
var player_move = "5/7/9";
var translated_pm = player_move.replace(/\/\*?/, 25 - /$1/);
Thank you!
Try this, all in one line:
var player_move = "5/7/9";
var new_move = player_move.split('/').map(function(number) { return 25 - Number(number); }).join('/');
alert(new_move);
Do you have to use a regex?
JsBin example
without regex
This might be a better way to do it:
var n = "4/7/12".split('/').map(function(el) {
return 25 - Number(el); // Number not needed here bc of coercion but I like it here
}).join('/');
regexp
With .replace, you can pass in a function like so:
var re = "4/7/12".replace(/\d+/g, function(match) {
return 25 - match;
})
Try this
var translated_pm = player_move.replace(/\d+/g, function (x){return 25 - parseInt(x)});
I have a string as a1234b5.
I am trying to get 1234 (in between a and b5). i tried the following way
number.replace(/[^0-9\.]/g, '');
But it's giving me like 12345. But I need 1234. how to achieve this in Javascript ?
You can use:
var m = 'a1234b5'.match(/\d+/);
if (m)
console.log(m[0]);
//=> "1234"
slighty different approach
var a = "a1234b5243,523kmw3254n293f9823i32lia3un2al542n5j5j6j7k7j565h5h2ghb3bg43";
var b;
if ( typeof a != "undefined" )
{
b = a.match( /[0-9]{2,}/g );
console.log( b );
}
no output if a isn't set.
if a is empty => null
if somethings found => ["1234", "5243", "523", "3254", "293", "9823", "32", "542", "565", "43"]
Assuming that there are always letters around the numbers you want and that you only care about the very first group of numbers that are surrounded by letters, you can use this:
("abc123456def1234ghi123".match(/[^\d](\d+)[^\d]/) || []).pop()
// "123456"
var number = 'a1234b5';
var firstMatch = number.match(/[0-9]+/);
var matches = number.match(/[0-9]+/g);
var without = matches.join('');
var withoutNum = Number(without);
console.log(firstMatch); // ["1234"]
console.log(matches); // ["1234","5"]
console.log(without); // "12345"
console.log(withoutNum); // 12345
I have a feeling that number is actually a hexadecimal. I urge you to update the question with more information (i.e. context) than you're providing.
It's not clear if a and b are always part of the strings you are working with; but if you want to 'extract' the number out, you could use:
var s = "a1234b5",
res = s.match(/[^\d](\d+)[^\d]/);
// res => ["a1234b", "1234"]
then, you could reassign or do whatever. It's not clear what your intention is based on your use of replace. But if you are using replace to convert that string to just the number inside the [a-z] characters, this would work:
s.replace(/[^\d](\d+)[^\d](.*)$/, "$1")
But, that's assuming the first non-digit character of the match has nothing before it.