How to get matching Regex content in JavaScript? - javascript

Given the string,
#[pill(hello.0.LastName)]
How do I get hello.0.LastName?
Here is Regex Pattern:
const dataPillRegex = /#\[hello\((.*?)\)\]/g;

Here’s a solution, output is an array with various different pieces of information in it, but the only piece you need is output[1]. Nevertheless, I would still recommend logging the whole of output to the console so you can see what’s in there.
const input = "#[pill(hello.0.LastName)]";
output = input.match(/#\[pill\((.+)\)\]/);
console.log(output[1]);
Output:
hello.0.LastName
You could also add a g to the end of the regex string if you don’t want the excess data:
const input = "#[pill(hello.0.LastName)]";
output = input.match(/#\[pill\((.+)\)\]/g);
console.log(output[0]);
Output:
hello.0.LastName

Related

Regex for detecting emojis with condition

Let's say we have a string variable which could have emojis in it. I'm trying to find a way to pick those strings which:
Doesn't have anything other than emojis
Doesn't have more than 5 emojis
This repo works pretty well in terms of detecting all kinds emojis, but I'm wondering how can I apply my rules on its regex.
const myRegex = "??"
const mString1 = "😍🥳😍"
myRegex.test(mString1) // true
const mString2 = "😍Text👨‍💻"
myRegex.test(mString2) // false
const mString3 = "😍😍😂💪😍😍"
myRegex.test(mString3) // false
So, basically what you want is the following:
// detects if string consists of 0 to 5 emojis
const regex = /^(emoji){0,5}$/;
Now the only missing part is the actual emoji-detection inside that regex. We can extract this out of this emoji-regex library you referenced:
const emojiRegex = require('emoji-regex/RGI_Emoji.js');
const regex = new RegExp("^(" + emojiRegex().source + "){0,5}$", emojiRegex().flags);
Didn't test, but something like this should work.

Javascript regex parse complex url string

I need to parse a complex URL string to fetch specific values.
From the following URL string:
/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss
I need to extract this result in array format:
['http://any-feed-url-a.com?filter=hot&format=rss', 'http://any-feed-url-b.com?filter=rising&format=rss']
I tried already with this one /url=([^&]+)/ but I can't capture all correctly all the query parameters. And I would like to omit the url=.
RegExr link
Thanks in advance.
This regex works for me: url=([a-z:/.?=-]+&[a-z=]+)
also, you can test this: /http(s)?://([a-z-.?=&])+&/g
const string = '/api/rss/feeds?url=http://any-feed-url.com?filter=hot&format=rss&url=http://any-feed-url.com?filter=latest&format=rss'
const string2 = '/api/rss/feeds?url=http://any-feed-url.com?filter=hot&format=rss&next=parm&url=http://any-feed-url.com?filter=latest&format=rss'
const regex = /url=([a-z:/.?=-]+&[a-z=]+)/g;
const regex2 = /http(s)?:\/\/([a-z-.?=&])+&/g;
console.log(string.match(regex))
console.log(string2.match(regex2))
have you tried to use split method ? instead of using regex.
const urlsArr = "/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss".split("url=");
urlsArr.shift(); // removing first item from array -> "/api/rss/feeds?"
console.log(urlsArr)
)
which is going to return ["/api/rss/feeds?", "http://any-feed-url-a.com?filter=hot&format=rss&", "http://any-feed-url-b.com?filter=rising&format=rss"] then i am dropping first item in array
if possible its better to use something else then regex CoddingHorror: regular-expressions-now-you-have-two-problems
You can matchAll the url's, then map the capture group 1 to an array.
str = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss'
arr = [...str.matchAll(/url=(.*?)(?=&url=|$)/g)].map(x => x[1])
console.log(arr)
But matchAll isn't supported by older browsers.
But looping an exec to fill an array works also.
str = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss'
re = /url=(.*?)(?=&url=|$)/g;
arr = [];
while (m = re.exec(str)) {
arr.push(m[1]);
}
console.log(arr)
If your input is better-formed in reality than shown in the question and you’re targeting a modern JavaScript environment, there’s URL/URLSearchParams:
const input = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot%26format=rss&url=http://any-feed-url-b.com?filter=rising%26format=rss';
const url = new URL(input, 'http://example.com/');
console.log(url.searchParams.getAll('url'));
Notice how & has to be escaped as %26 for it to make sense.
Without this input in a standard form, it’s not clear which rules of URLs are still on the table.

regex to match first occruence and everything in between until last match

I may be thinking this about the wrong way.
The first three (...)'s are generated and could be any number. I only want to catch these first set of items and allow the user to use () inside of their custom string.
Test String
(374003) (C6-96738) (WR183186) R1|SALOON|DEFECTIVE|WiFiInfotainment|Hardware detects WIFI but unable to log in on the (JAMIE HUTBER) internet.:
Regex
/\(([^)]+)\)/g
Current output
 ["(374003)", "(C6-96738)", "(WR183186)", "(JAMIE HUTBER)"]
Desired Output
 ["(374003)", "(C6-96738)", "(WR183186)"]
You can use two ways to do that:
get only 3 items from array
add space to your regexp \(([^ )]+)\) (https://regex101.com/r/ZPdq35/1/)
Using the sticky option /y you can then use regEx's ability to find all occurrences..
This will then work, if there is not a space in JAMIE HUNTER, etc..
eg.
const re = /\s*\(([^)]+)\)/y;
const str = "(374003) (C6-96738) (WR183186) R1|SALOON|DEFECTIVE|WiFiInfotainment|Hardware detects WIFI but unable to log in on the (JAMIE HUTBER) internet.:";
let m = re.exec(str);
while (m) {
console.log(m[1]);
m = re.exec(str);
}

Pick out words in a string that are in array

I have spent hours, close to 8 hours none stop on this, I am trying to use jQuery/JS to create two arrays, one which is dynamic as it is loading a chat script and will be split by whitespace in to an array, for example:
String: Hello my name is Peter
Converted to (message) array: ['hello','my','name','is','peter'];
I have a set array to look out for specific words, in this example let us use:
(find array) ['hello','peter'] however, this array is going to contain up to 20 elements and I need to ensure it searches the message array efficiently, please help.
I can help you with that.
var arrayOfWords = $(".echat-shared-chat-message-body").last().text().split(" ");
That code is actually working! i went to an open chat in this website so I can tested.
So just replace the word REPLACE with your DOM object :)
var arrayOfWords = $("REPLACE").last().text().split(" ");
If I understood well, you're asking to filter an array of string (from an incoming string) given a second array.
In your described case you'll certainly not have to worry about efficiency, really. Unless your incoming message is allowed to be very very big.
Given that, there is a dozen of options, I think this is the most succinct:
const whitelist = [
'hello',
'peter'
]
const message = 'hello my name is Peter'.split(' ')
const found = message.filter(function(word) {
return whitelist.indexOf(word) > -1
}
You can treat invariant case:
const whitelistLower = whitelist.toLowerCase()
const foundInvariantCase = message.filter(function(word) {
return whitelist.indexOf(word.toLowerCase()) > -1
}
Or use ESS Set:
const whitelistSet = new Set(whitelist)
const found = message.filter(function(word) {
return whitelistSet.has(word)
}

RegExp doesn't produce expected result but it does everywhere else [duplicate]

This question already has answers here:
RegEx to extract all matches from string using RegExp.exec
(19 answers)
Closed 5 years ago.
I'm getting started with Node.js and trying to learn it, coming from PHP environment.
I have following RegExp: /([A-Z]{2,})+/gim (two or more letters next to each other).
I have following string: "That's my testing sample but it doesn't work."
So I throw this into Node.js (keep in mind I'm a newbie):
var fs = require("fs");
var request = require("request");
// COMMENTS
var regex = new RegExp(/([A-Z]{2,})+/gim);
//COMMENTS
var thisyear = regex.exec("That's my testing sample but it doesn't work.");
console.log(thisyear);
This is the file in it's entirety.
The output that it returns:
[ 'That',
'That',
index: 0,
input: 'That\'s my testing sample but it doesn\'t work.' ]
The output according to pretty much every site I tested it on:
That
my
testing
sample
but
it
doesn
work
How do I get each separate result in an array of sorts?
P.S.: match() and test() are "not a function".
To get multiple results with the g flag, you call .exec() multiple times like this:
let regex = /([A-Z]{2,})+/gim;
let str = "That's my testing sample but it doesn't work.";
let results;
while ((results = regex.exec(str)) !== null) {
console.log(results[0]);
}
Javascript will set the .index property on the regex object to keep track of where it is searching in the source string and each time you call it, it will return the next set of results.
Note: When using the literal form of a regex /something/, you do not put it inside a new RegExp() constructor. The language makes you a regex object automatically when using the literal syntax.
FYI, you can get all the matches without using a while look like this:
let re = /([A-Z]{2,})+/gim;
let str = "That's my testing sample but it doesn't work.";
console.log(str.match(re));
This is generally the simpler way to do it unless you need to get the groups from your regex. If you need to groups rather than just the whole match, then you have to use the .exec() form to get multiple matches, each with multiple groups.

Categories