Removing elements of string before a specific repeated character in it in javascript - 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.

Related

Use only one of the characters in regular expression javascript

I guess that should be smth very easy, but I'm stuck with that for at least 2 hours and I think it's better to ask the question here.
So, I've got a reg expression /&t=(\d*)$/g and it works fine while it is not ?t instead of &t in url. I've tried different combinations like /\?|&t=(\d*)$/g ; /\?t=(\d*)$|/&t=(\d*)$/g ; /(&|\?)t=(\d*)$/g and various others. But haven't got the expected result which is /\?t=(\d*)$/g or /&t=(\d*)$/g url part (whatever is placed to input).
Thx for response. I think need to put some details here. I'm actually working on this peace of code
var formValue = $.trim($("#v").val());
var formValueTime = /&t=(\d*)$/g.exec(formValue);
if (formValueTime && formValueTime.length > 1) {
formValueTime = parseInt(formValueTime[1], 10);
formValue = formValue.replace(/&t=\d*$/g, "");
}
and I want to get the t value whether reference passed with &t or ?t in references like youtu.be/hTWKbfoikeg?t=82 or similar one youtu.be/hTWKbfoikeg&t=82
To replace, you may use
var formValue = "some?some=more&t=1234"; // $.trim($("#v").val());
var formValueTime;
formValue = formValue.replace(/[&?]t=(\d*)$/g, function($0,$1) {
formValueTime = parseInt($1,10);
return '';
});
console.log(formValueTime, formValue);
To grab the value, you may use
/[?&]t=(\d*)$/g.exec(formValue);
Pattern details
[?&] - a character class matching ? or &
t= - t= substring
(\d*) - Group 1 matching zero or more digits
$ - end of string
/\?t=(\d*)|\&t=(\d*)$/g
you inverted the escape character for the second RegEx.
http://regexr.com/3gcnu
I want to thank you all guys for trying to help. Special thanks to #Wiktor Stribiżew who gave the closest answer.
Now the piece of code I needed looks exactly like this:
/[?&]t=(\d*)$/g.exec(formValue);
So that's the [?&] part that solved the problem.
I use array later, so /\?t=(\d*)|\&t=(\d*)$/g doesn't help because I get an array like [t&=50,,50] when reference is & type and the correct answer [t?=50,50] when reference is ? type just because of the order of statements in RegExp.
Now, if you're looking for a piece of RegExp that picks either character in one place while the rest of RegExp remains the same you may use smth like this [?&] for the example where wanted characters are ? and &.

How would I write a Regular Expression to capture the value between Last Slash and Query String?

Problem:
Extract image file name from CDN address similar to the following:
https://cdnstorage.api.com/v0/b/my-app.com/o/photo%2FB%_2.jpeg?alt=media&token=4e32-a1a2-c48e6c91a2ba
Two-stage Solution:
I am using two regular expressions to retrieve the file name:
var postLastSlashRegEx = /[^\/]+$/,
preQueryRegEx = /^([^?]+)/;
var fileFromURL = urlString.match(postLastSlashRegEx)[0].match(preQueryRegEx)[0];
// fileFromURL = "photo%2FB%_2.jpeg"
Question:
Is there a way I can combine both regular expressions?
I've tried using capture groups, but haven't been able to produce a working solution.
From my comment
You can use a lookahead to find the "?" and use [^/] to match any non-slash characters.
/[^/]+(?=\?)/
To remove the dependency on the URL needing a "?", you can make the lookahead match a question mark or the end of line indicator (represented by $), but make sure the first glob is non-greedy.
/[^/]+?(?=\?|$)/
You don't have to use regex, you can just use split and substr.
var str = "https://cdnstorage.api.com/v0/b/my-app.com/o/photo%2FB%_2.jpeg?alt=media&token=4e32-a1a2-c48e6c91a2ba".split("?")[0];
var fileName = temp.substr(temp.lastIndexOf('/')+1);
but if regex is important to you, then:
str.match(/[^?]*\/([^?]+)/)[1]
The code using the substring method would look like the following -
var fileFromURL = urlString.substring(urlString.lastIndexOf('/') + 1, urlString.lastIndexOf('?'))

JavaScript RegEx to match url path

I have possible url paths as below
/articles
/payment
/about
/articles?page=1
/articles/hello-world
I would like to match only the main path of the url, expected matches: ['articles', 'payment', 'about', 'articles', 'articles']
So I tried to construct the JavaScript RegEx and came up with as nearest as I can [a-z].*(?=\/|\?), unfortunately it only matches string inside the last two
Please guide
Thanks everyone
https://regex101.com/r/A86hYz/1
/^\/([^?\/]+)/
This regex captures everything between the first / and either the second / or the first ? if they exist. This seems like the pattern you want. If it isn't, let me know and I'll adjust it as needed. Some simple adjustments would be capturing what's between every / as well as capturing the query parameters.
For future reference, when writing regex, try to avoid the lookahead/behind unless you have to as they usually introduce bugs. It's easiest if you stick to using the regular operators.
To access the match, use the regex like this:
var someString = '/articles?page=1';
var extracted = someString.match(/^\/([^?\/]+)/)[1]
or more generally
function getMainPath(str) {
const regex = /^\/([^?\/]+)/;
return str.match(regex)[1];
}

Is it possible to cut off the beginning of a string using regex?

I have a string which contains a path, such as
/foo/bar/baz/hello/world/bla.html
Now, I'd like to get everything from the second-last /, i.e. the result shall be
/world/bla.html
Is this possible using a regex? If so, how?
My current solution is to split the string into an array, and join its last two members again, but I'm sure that there is a better solution than this.
For example:
> '/foo/bar/baz/hello/world/bla.html'.replace(/.*(\/.*\/.*)/, "$1")
/world/bla.html
You can also do
str.split(/(?=\/)/g).slice(-2).join('')
> '/foo/bar/baz/hello/world/bla.html'.match(/(?:\/[^/]+){2}$/)[0]
"/world/bla.html"
Without regular expression:
> var s = '/foo/bar/baz/hello/world/bla.html';
> s.substr(s.lastIndexOf('/', s.lastIndexOf('/')-1))
"/world/bla.html"
I think this will work:
var str = "/foo/bar/baz/hello/world/bla.html";
alert( str.replace( /^.*?(\/[^/]*(?:\/[^/]*)?)$/, "$1") );
This will allow for there being possibly only one last part (like, "foo/bar").
You can use /(\/[^\/]*){2}$/ which selects a slash and some content twice followed by the end of the string.
See this regexplained.

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