Extract substring from a string using regex in javascript - javascript

I am new to javascript, How to extract substring that matches a regex in a string in javascript?
For example in python:
version_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)')
line = "[2021-05-29] Version 2.24.9"
found = version_regex.search(line)
if found:
found.group() // It will give the substring that macth with regex in this case 2.24.9
I tried these in javascript:
let re = new RegExp('^(\d+)\.(\d+)\.(\d+)$');
let x = line.match(re);
but I am not getting the version here.
Thanks in advance.

You can use RegExp.prototype.exec which returns an Array with the full match and the capturing groups matches:
const input = '[2021-05-29] Version 2.24.9';
const regex = /(\d+)\.(\d+)\.(\d+)/;
let x = regex.exec(input);
console.log(x);

Related

Getting the content between two characters

So I have this (example) string: 1234VAR239582358X
And I want to get what's in between VAR and X. I can easily replace it using .replace(/VAR.*X/, "replacement");
But, how would I get the /VAR.*X/as a variable?
I think what you are looking for might be
string.match(/VAR(.*)X/)[1]
The brackets around the .* mark a group. Those groups are returned inside the Array that match creates :)
If you want to only replace what's in between "VAR" and "X" it would be
string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");
Or more generic:
string.replace(/(VAR).*(X)/, "$1replacement$2");
You can try use the RegExp class, new RegExp(`${VAR}.*X`)
You can store it as variable like this,
const pattern = "VAR.*X";
const reg = new RegExp(pattern);
Then use,
.replace(reg, "replacement");
If you
want to get what's in between VAR and X
then using .* would do the job for the given example string.
But note that is will match until the end of the string, and then backtrack to the first occurrence of X it can match, being the last occurrence of the X char in the string and possible match too much.
If you want to match only the digits, you can match 1+ digits in a capture group using VAR(\d+)X
const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
Or you can match until the first occurrence of an X char using a negated character class VAR([^\r\nX]+)X
const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}

How to rewrite this RegExp to not use deprecated API?

I have the following RegExp myRegexp, that matches numbers in a string:
var myRegexp = new RegExp('[0-9]+');
Then I have the following code that extracts numbers from a string and returns an array:
var string = '123:456';
var nums = new Array();
while(myRegexp.test(string)) {
nums.length++;
nums[nums.length - 1] = RegExp.lastMatch;
string = RegExp.rightContext;
}
Should return an array of two elements: "123", and "456".
However, RegExp.lastMatch and RegExp.rightContext are deprecated/non-standard API, and not portable. How can I rewrite this logic using portable JS API?
Thanks,
To match all numbers in a string, you'd simply use string.match(/\d/g); to match all single digits in a separate array entry, or string.match(/\d+/g); to match as numbers. There's no need for any of the things you've tried to useā€¦
let string = "2kdkane2kdkie83kdkdk303ldld";
let match = string.match(/\d+/g);
let match1 = string.match(/\d/g);
console.log('numbers:', match);
console.log('single digits:', match1);
Use the g flag to perform a global match which will find all matches without having to repeatedly test the string.
let s = '123:456'
const regexp = new RegExp(/\d+/g);
let nums = s.match(regexp);
console.log(nums);

How to check if part of string is present in array or not

I have got of array symbols as shown below
var sourcesymbols = ["ERT", "UBL" , "AMAZING"];
I am getting the following news title from rss feed
you experts are amazing
How to check if the content present in the rssfeedstring is present under the sourcesymbols array or not ??
For example rssfeedstring has word amazing and it is also present under sourcesymbols
please let me know how to achive this .
I have tried to convert the rssfeedstring to uppercase then i am not sure how to use the indexOf on the string .
rssfeedstring = rssfeedstring.toUpperCase();
please let em know if there is any better approach also for doing this as the array will have 2000 symbols
http://jsfiddle.net/955pfz01/3/
You can use regex.
Steps:
Convert the array to string with join using |(OR in regex) as glue
Use \b-word boundary to match exact words
Use i flag on regex to match irrespective of the case. So, don't have to change the case of string.
Escape the slashes as using RegExp constructor requires string to be passed and \ in string is used as escape following character.
test can be used on regex to check if the string passes the regex.
var sourcesymbols = ["ERT", "UBL", "AMAZING"];
var mystr = 'you experts are amazing';
var regex = new RegExp("\\b(" + sourcesymbols.join('|') + ")\\b", 'i'); // /\b(ERT|UBL|AMAZING)\b/i
alert(regex.test(mystr));
You can also use some
Convert the string to array by using split with \s+. This will split the string by any(spaces, tabs, etc) one or more space character
Use some on splitted array
Convert the string to uppercase for comparing
Check if the element is present in array using indexOf
var mystr = 'you experts are amazing';
var sourcesymbols = ["ERT", "UBL", "AMAZING"];
var present = mystr.toUpperCase().split(/\s+/).some(function(e) {
return sourcesymbols.indexOf(e) > -1;
});
alert(present);
Try using Array.prototype.map() , Array.prototype.indexOf() to return matched text, index of matched text within sourcesymbols
var sourcesymbols = ["ERT", "UBL" , "AMAZING"];
var mystr = 'you experts are amazing';
var res = mystr.split(" ").map(function(val, index) {
var str = val.toUpperCase(), i = sourcesymbols.indexOf(str);
return i !== -1 ? [val, i] : null
}).filter(Boolean);
console.log(res)
jsfiddle http://jsfiddle.net/955pfz01/6/

How to extract string in regex

I have string in this format:
var a="input_[2][invoiceNO]";
I want to extract "invoiceNo" string. I've tried:
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]');
var res = patt.exec(a);
However, I get the following output:
Array [ "[2]", "2" ]
I want to extract only invoiceNo from the string.
Note: Input start can be any string and in place of number 2 it can be any number.
I would check if the [...] before the necessary [InvoiceNo] contains digits and is preceded with _ with this regex:
/_\[\d+\]\s*\[([^\]]+)\]/g
Explanation:
_ - Match underscore
\[\d+\] - Match [1234]-like substring
\s* - Optional spaces
\[([^\]]+)\] - The [some_invoice_123]-like substring
You can even use this regex to find invoice numbers inside larger texts.
The value is in capture group 1 (see m[1] below).
Sample code:
var re = /_\[\d+\]\s*\[([^\]]+)\]/g;
var str = 'input_[2][invoiceNO]';
while ((m = re.exec(str)) !== null) {
alert(m[1]);
}
You can use this regex:
/\[(\w{2,})\]/
and grab captured group #1 from resulting array of String.match function.
var str = 'input_[2][invoiceNO]'
var m = str.match(/\[(\w{2,})\]/);
//=> ["[invoiceNO]", "invoiceNO"]
PS: You can also use negative lookahead to grab same string:
var m = str.match(/\[(\w+)\](?!\[)/);
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]$');
var res = patt.exec(a);
Try this:
var a="input_[2][invoiceNO]";
var patt = new RegExp(/\]\[(.*)\]/);
var res = patt.exec(a)[1];
console.log(res);
Output:
invoiceNO
You could use something like so: \[([^[]+)\]$. This will extract the content within the last set of brackets. Example available here.
Use the greediness of .*
var a="input_[2][invoiceNO]";
var patt = new RegExp('.*\[(.*?)\]');
var res = patt.exec(a);

find special text from string in javascript

I have string like #ls/?folder_path=home/videos/
how i can find last text from string? this place is videos
other strings like
#ls/?folder_path=home/videos/
#ls/?folder_path=home/videos/test/testt/
#ls/?folder_path=seff/test/home/videos/
We could use a few more example strings, but based off of your one and only example, here's a rough regex to get you started:
.*?/\?.*?/(.*?)\//
EDIT:
Based on your extended examples:
.*?/\?.*/(.*?)\//
This regex will consume text until the second to last / and capture until the last / in the string.
This will work even if the string doesn't end in /
var str;
var re = /\w+(?=\/?$)/;
str = "#ls/?folder_path=home/videos/"
str.match(re) ; //# => videos
str = "#ls/?folder_path=home/videos/test/testt/"
str.match(re) ; //# => testt
str = "#ls/?folder_path=seff/test/home/videos/"
str.match(re) ; //# => videos
str = "#ls/?folder_path=home/videos/test/testt"
str.match(re) ; //# => testt
\/([^\/]*)\/?$
This regex will match all non / between the last two /. Where the last / is optional. The $ is matching the end of the string.
Your resulting string is then in the first capturing group (because of the ()) $1
You can test it here
There are many ways to do this. One of them:
var str = '#ls/?folder_path=home/videos/'.replace(/\/$/,'');
alert(str.substr(str.lastIndexOf('/')+1)); //=> videos
Alternative without using replace
var str = '#ls/?folder_path=home/videos/'
,str = str.substr(0,str.length-1)
,str = str.substr(str.lastIndexOf('/')+1);
alert(str); //=> videos
If your data is consistent like this string, this is a simple split based way to retreive
your required string: http://jsfiddle.net/EEkLP/
var str="#ls/?folder_path=home/videos/";
var strArr = str.split("/");
alert(strArr[strArr.length-2]);
If it always ends with / then this will works.
var str = '#ls/?folder_path=home/videos/';
var arr = str.split('/');
var index = arr.length-2;
console.log(arr[index]);
If the last word always enclosed with forward slashes, then you can try this -
".+\/([^\/]+)\/$"
or in regex notation
/.+\/([^\/]+)\/$/

Categories