regex matching string in between string - javascript

I have always found regex hard. I am sorry but I had to ask,
https://meet.google.com/zzz-tssd-trt?authuser=1
https://meet.google.com/zzz-tssd-trt
https://meet.google.com/zzz44-5454ws-fgaf
How would I get the code, for instance zzz44-5454ws-fgaf or zzz-tssd-trt or zzz-tssd-trt from these strings?

No need to use Regex. Much safer to use URL
const paths = `https://meet.google.com/zzz-tssd-trt?authuser=1
https://meet.google.com/zzz-tssd-trt
https://meet.google.com/zzz44-5454ws-fgaf`
.split(/\n/).map(url => new URL(url).pathname)
console.log(paths)

You can use the regex \w(?=/)/([^?|\n]+) this regwx will group all the charctes after the last / and before ? or new line.
import re
s = """
https://meet.google.com/zzz-tssd-trt?authuser=1
https://meet.google.com/zzz-tssd-trt
https://meet.google.com/zzz44-5454ws-fgaf
"""
print(re.findall(r"\w(?=/)/([^?|\n]+)", s))
Output
['zzz-tssd-trt', 'zzz-tssd-trt', 'zzz44-5454ws-fgaf']

'https://meet.google.com/[a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{3}','gi'
this is more restrictive and worked well for me.

Related

.replace not replacing all chars [NODEJS]

I've searched all around the web for a response to this question,
Why do my .replace only replace chars that doesnt have any other char behind
My code is :
const fixedstring = string.replace('&', '^&')
When i enter : &notepad.exe& has a string, it give me the output ^&notepad.exe& instead of ^&notepad.exe^&
Can someone help me ? (i've tried the /g)
Thanks for the guy that will help me or just read my post, thanks !
You can't use the global flag /g unless you are using regex to find the characters to replace. You are currently using a string to find, which will only match the first instance.
Instead, use the regex:
.replace(/&/g, "^&")
Here is a working example.
const stringToReplace = "&notepad.exe&"
const replaced = stringToReplace.replace(/&/g, '^&')
console.log(replaced)

Regex that only matches when 4 specific words were found

As the title says, I need a Regex to check if a string has this four words (Update, Rollback, Skip, Not Now) and only return them if all of them are present, if not it doesn’t return anything.
Here is an example:
{"Update":"iVBORw0KGgo","Rollback":"iVBORw0KGgo","Skip":"iVBORw0KGgo","Not Now":"iVBORw0KGgo"}
In this case, it should return [Update, Rollback, Skip, Not Now]
{"Update":"iVBORw0KGgo","Skip":"iVBORw0KGgo","Not Now":"iVBORw0KGgo"}
In this case, it shouldn’t return any value
I tried to create one by myself but my knowledge of Regex is very basic:
(Update|Rollback|Skip|Not Now)
Thanks in advance!
EDIT
I noticed that Regex might not be the best way to achieve this.
Use this:
^(?=.*"Update"\s*:)(?=.*"Rollback"\s*:)(?=.*"Skip"\s*:)(?=.*"Not Now"\s*:)
(?=...) means that if you lookahead, you find this pattern.
So an empty match will return as soon as we find all these 4 patterns.
demo
As an alternative to regex, you can use JSON.parse to parse the string into an object and Object.keys to get the properties:
const str = `{"Update":"iVBORw0KGgo","Rollback":"iVBORw0KGgo","Skip":"iVBORw0KGgo","Not Now":"iVBORw0KGgo"}`;
const keys = Object.keys(JSON.parse(str))
const result = keys.sort().toString() == "Not Now,Rollback,Skip,Update" ? keys : "";
console.log(result)
While regex is clearly not a good tool for the job,
you can do something like this:
re.match("(?=.*Update.*)(?=.*Skip.*)",string)
"(?=WORD)" matches if the expression follows, but doesn't consume any of the string.
Of course, complete the regex by all 4 words that you want similarly.
Also notice that regex by itself doesn't return anything. You need to code for this.

Removing elements of string before a specific repeated character in it in javascript

I'm trying to remove from my string all elements before an specific character which is repeated several times in this way:
let string = http://localhost:5000/contact-support
thus I´m just trying to remove everything before the third /
having as result:contact_support
for that i just set:
string.substring(string.indexOf('/') + 3);
Bust guess thats not the correct way
Any help about how to improve this in the simplest way please?
Thanks in advance!!!
It seems like you want to do some URL parsing here. JS brings the handful URL utility which can help you with this, and other similar tasks.
const myString = 'http://localhost:5000/contact-support';
const pathname = new URL(myString).pathname;
console.log(pathname); // outputs: /contact-support
// then you can also remove the first "/" character with `substring`
const whatIActuallyNeed = pathname.substring(1, pathname.length);
console.log(whatIActuallyNeed); // outputs: contact-support
Hope This will work
string.split("/")[3]
It will return the sub-string after the 3rd forward slash.
You could also use lastIndexOf('/'), like this:
string.substring(string.lastIndexOf('/') + 1);
Another possibility is regular expressions:
string.match(/[^\/]*\/\/[^\/]*\/(.*)/)[1];
Note that you must escape the slash, since it is the delimiter in regular expressions.
string.substring(string.lastIndexOf('/')+1) will also do the job if you are looking to use indexOf function explicitly.

regex to remove certain characters at the beginning and end of a string

Let's say I have a string like this:
...hello world.bye
But I want to remove the first three dots and replace .bye with !
So the output should be
hello world!
it should only match if both conditions apply (... at the beginning and .bye at the end)
And I'm trying to use js replace method. Could you please help? Thanks
First match the dots, capture and lazy-repeat any character until you get to .bye, and match the .bye. Then, you can replace with the first captured group, plus an exclamation mark:
const str = '...hello world.bye';
console.log(str.replace(/\.\.\.(.*)\.bye/, '$1!'));
The lazy-repeat is there to ensure you don't match too much, for example:
const str = `...hello world.bye
...Hello again! Goodbye.`;
console.log(str.replace(/\.\.\.(.*)\.bye/g, '$1!'));
You don't actually need a regex to do this. Although it's a bit inelegant, the following should work fine (obviously the function can be called whatever makes sense in the context of your application):
function manipulate(string) {
if (string.slice(0, 3) == "..." && string.slice(-4) == ".bye") {
return string.slice(4, -4) + "!";
}
return string;
}
(Apologies if I made any stupid errors with indexing there, but the basic idea should be obvious.)
This, to me at least, has the advantage of being easier to reason about than a regex. Of course if you need to deal with more complicated cases you may reach the point where a regex is best - but I personally wouldn't bother for a simple use-case like the one mentioned in the OP.
Your regex would be
const rx = /\.\.\.([\s\S]*?)\.bye/g
const out = '\n\nfoobar...hello world.bye\nfoobar...ok.bye\n...line\nbreak.bye\n'.replace(rx, `$1!`)
console.log(out)
In English, find three dots, anything eager in group, and ending with .bye.
The replacement uses the first match $1 and concats ! using a string template.
An arguably simpler solution:
const str = '...hello world.bye'
const newStr = /...(.+)\.bye/.exec(str)
const formatted = newStr ? newStr[1] + '!' : str
console.log(formatted)
If the string doesn't match the regex it will just return the string.

javascript jquery regexp replace

I'm trying to create a dynamic searchbar and i need help.
Right now im trying to replace a string with another string but i cant seem to succeed.
Im getting input from the user:
var location_keyword = $("#si_user_location").val();
Now i would like to replace a whitespace " " with a "|" to use this in my regexp as OR.
For example if the user wrote "Turkey Alanya", i want it to be "Turkey|Alanya" so that the search hits for both Turkey OR Alanya.
i tried something like this but it didnt work
var location_keyword = $("#si_user_location").val();
location_keyword.replace(" ","|");
var regexp_loc = new RegExp(location_keyword, "i");
i used to do this in PHP before with expressions such as:
preg_replace('/'.preg_quote($keyword).'/i', "<span>$0</span>", $string)
and i could replace strings caseinsensetive like this, how can i do this in js?
I used the last expression in PHP to highlight the keyword in the results, which i would like to do aswell in js.
hope i can get some help, thanks in advance! :)
best of regards,
alexander
There are two problems with the use of replace on this line:
location_keyword.replace(" ","|");
It does not modify the string - it returns a new string. You need to reassign the result of the call to the original variable otherwise you won't see the changed string.
It only replaces the first occurrence unless you use a regular expression with the g (global) flag.
Try this instead:
location_keyword = location_keyword.replace(/ /g, '|');
Try this:
location_keyword = location_keyword.replace(/\s+/,"|");
This should work fine:
location_keyword.replace(/ /g,"|");
Hope this helps! :)

Categories

Resources