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

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.

Related

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.

Matching everything after first pipe character in Javascript RegEx

I have this string:
"http://www.yahoo.com/abc/123|X|Y|Z"
I need to get everything after the first pipe with a regex. So I would want to be left with this string:
"X|Y|Z"
How do I do this in JavaScript?
Using a simpler regex /\|(.*)/
var str = "http://www.yahoo.com/abc/123|X|Y|Z";
var aryMatches = str.match(/\|(.*)/);
// aryMatches[1] will have your results
regex explaination
Converting my comment to an answer:
Shockingly, regexes are not the answer to everything.
> xkcd
Try this:
str.split("|").slice(1).join("|");
This splits your string on pipe characters, slices off the first item, then joins the rest with pipes again.
First group contains the expected characters,
^.*?\|(.*)$
DEMO
You can use this regex:
/^[^|]*\|(.*)/
And use matched group #1 for your match.
Forget the splitting and splicing, just use a substring
var str = "http://www.yahoo.com/abc/123|X|Y|Z";
str.substr(str.indexOf("|") + 1);

Extract specific chars from a string using a regex

I need to split an email address and take out the first character and the first character after the '#'
I can do this as follows:
'bar#foo'.split('#').map(function(a){ return a.charAt(0); }).join('')
--> bf
Now I was wondering if it can be done using a regex match, something like this
'bar#foo'.match(/^(\w).*?#(\w)/).join('')
--> bar#fbf
Not really what I want, but I'm sure I miss something here! Any suggestions ?
Why use a regex for this? just use indexOf to get the char at any given position:
var addr = 'foo#bar';
console.log(addr[0], addr[addr.indexOf('#')+1])
To ensure your code works on all browsers, you might want to use charAt instead of []:
console.log(addr.charAt(0), addr.charAt(addr.indexOf('#')+1));
Either way, It'll work just fine, and This is undeniably the fastest approach
If you are going to persist, and choose a regex, then you should realize that the match method returns an array containing 3 strings, in your case:
/^(\w).*?#(\w)/
["the whole match",//start of string + first char + .*?# + first string after #
"groupw 1 \w",//first char
"group 2 \w"//first char after #
]
So addr.match(/^(\w).*?#(\w)/).slice(1).join('') is probably what you want.
If I understand correctly, you are quite close. Just don't join everything returned by match because the first element is the entire matched string.
'bar#foo'.match(/^(\w).*?#(\w)/).splice(1).join('')
--> bf
Using regex:
matched="",
'abc#xyz'.replace(/(?:^|#)(\w)/g, function($0, $1) { matched += $1; return $0; });
console.log(matched);
// ax
The regex match function returns an array of all matches, where the first one is the 'full text' of the match, followed by every sub-group. In your case, it returns this:
bar#f
b
f
To get rid of the first item (the full match), use slice:
'bar#foo'.match(/^(\w).*?#(\w)/).slice(1).join('\r')
Use String.prototype.replace with regular expression:
'bar#foo'.replace(/^(\w).*#(\w).*$/, '$1$2'); // "bf"
Or using RegEx
^([a-zA-Z0-9])[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#([a-zA-Z0-9-])[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$
Fiddle

Replace string into another string

I have a string, part of which looks like this:
"..devices=233.423.423.553&..."
and I'd like to replace the values of "devices=" with different values like "111.111" so it would appear like:
"..devices=111.111&..."
I think I can do that with some sort of expressions since I need to do that inline.Any trick would be appreciated..
Sure.. Just replace with the string you want to replace with:
var str = '..devices=233.423.423.553&...';
str = str.replace(/devices=[0-9.]+/g, 'devices=111.111');
console.log(str); //..devices=111.111&...
Autopsy:
devices= the literal string devices=
[0-9.]+ the digits 0 to 9 or the literal character . matched 1 to infinity times
/g means "global". Will replace any occurence rather than just the first one
I'm a relative noob, so forgive me if this is completely inefficient, but how about:
var myStr="..devices=233.423.423.553&..."
var something=myStr.substring((myStr.indexOf("=")+1),(myStr.indexOf("&")));
myStr.replace(something,"111.111.111");
Using regular expressions looks cooler, though.
Just try with:
"..devices=233.423.423.553&...".replace(/(devices)=(?:\d+(\.\d+)*)/, '$1=111.111')

Simple javascript regex

I need: www.mydomain.com:1235 form the text var below:
var text = 'http://www.mydomain.com:1235/;image.jpg';
alert(text.match(/\/[^]+\//));
output is: //www.mydomain.com:1235/
How do I exclude the delimiters?
You need to use parens to group what you want to match. Then, the call to .match() will let you use indexers. Index 0 is the whole string match, and index 1 is the first paren grouping.
var text = 'http://www.mydomain.com:1235/;image.jpg';
alert(text.match(/\/([^\/]+)\//)[1]);
Not a regex, but you could do this:
Example: http://jsfiddle.net/nTmv9/
text = text.split('http://')[1].split('/')[0];
or with a regex:
Example: http://jsfiddle.net/nTmv9/1/
text = text.match(/http:\/\/([^\/]+)\//)[1];
This will capture the domain without the http or the url slugs.
https?:\/\/([^\/]+)\/
If you need help figuring out regex here is a great tool I use all of the time.
http://gskinner.com/RegExr/
Cheers

Categories

Resources