javascript finding part of a string - javascript

I'm not very used to Javascript so I'm having trouble manipulating strings...
If I have something like /folder1/folder2/folder3/ , how do I parse it so I end up with just the current folder, e.g. "folder3" ?
Thanks!

var folderName = str.match(/(folder\d+)\/$/)[1];
Should do it.
Explanation of the regex:
( -> Start of capture group. We want a capture group because we just want
the folder name without the trailing slash.
folder -> Match the string "folder"
\d+ -> Match one or more digits
) -> End of capture group. This lets us capture strings of the form
"folderN", where N is a number.
\/ -> Escape forward slash. We have to escape this because / is used to
represent the start and end of a regex literal, in Javascript.
$ -> Match the end of the string.
The reason we are selecting the second element of the array (at index 1) is because the first element contains the complete string that was matched. This is not what we want; we just want the capture group. We only have one group that we captured, and so that is the second element.

Well, just because it's an option (though not necessarily sane):
var string = '/folder1/folder2/folder3/',
last = string.replace(/\//g,' ').trim().split(/\s/).pop();
console.log(last);
JS Fiddle demo.

You can use the split function to retrieve all subpaths:
var path = '/folder1/folder2/folder3/';
var paths = path.split('/');
var pathNeeded = paths[paths.length - 2];
Working example

How stable is the format of that string?
With a trailing slash you will need the next to last item
var parts = URL.split("/"); alert(parts[parts.length-2]);

var str = "/folder1/folder2/folder3/",
folder = str.substring(0, str.length - 1).split('/').pop();
FIDDLE

The split function transform your string into an array using the supplied parameter as a delimiter.
Therefore:
var parts = "/folder1/folder2/folder3/".split("/");
Will result in parts being equal to:
["", "folder1", "folder2", "folder3", ""]
You could then access each item using:
parts[0] // returns ''
parts[1] // returns 'folder1'
parts[2] // returns 'folder2'
.. and so on. Read more on split here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split

You can write the following:
var myString = '/fold1/fold2/fold3';
var myArray = myString.split('/');
var last_element = myArray[myArray.length - 1];
See the doc split

Related

regex: replace dynamically a searched word

I want to replace file:///Downloads/project by a another word like a github link :
const string = 'file:///Downloads/project/users/controllers/users/controller.js';
I tried working with .replace a world by a world but i got in the problem that file:///Downloads/projectis a dynamic value that may change from time to time.
string.replace(/file\:\/\/Downloads\/project\/users\/controller.js/gi, 'https://gitlab.com')
So i want to search for the word project and replace from it backward by another path or word
To achieve expected result, use below option of using indexOf and substr and finally replacing with gitlab url
Get index of project
Get string from 0 to index of project
Replace string from step 2 with gitlab using replace option
const string = 'file:///Downloads/project/users/controllers/users/controller.js';
const index = string.indexOf('project')
console.log(string.replace(string.substr(0, index), 'https://gitlab.com/'))
codepen - https://codepen.io/nagasai/pen/qvjdEa?editors=1010
Using regex you can match the first group which includes /project and replace the first parenthesized capture group with your https://gitlab.com. Here p1 denotes first parenthesized capture group and p2 denotes second parenthesized capture group.
const str = 'file:///Downloads/project/users/controllers/users/controller.js';
const res = str.replace(/^(.|\/)+\w*project(.+)*/gi, function(match, p1, p2) {
return 'https://gitlab.com' + p2;
});
console.log(res);
you don't need a regex for that
const string = 'file:///Downloads/project/users/controllers/users/controller.js',
yourValue = "file:///Downloads/project/",
res = string.replace(yourValue, "https://gitlab.com/")
console.log(res)
'https://gitlab.com/' + string.substr(string.indexOf('project'))
First find the position of 'project' in your string
string.indexOf('project')
then get a substring from that position to the end of the string (substr goes till the end when no second arg is provided)
string.substring(indexOfProject)
then concat it with '+'. Note that the url ends with '/' because your string will begin with 'p'.
'https://gitlab.com/' + extractedString

regex get part of the link

https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/
need to get "This-Part-I-Need-To-Get", with "-" symbols and capital letters at the wordstart.
All I managed to do is "/([A-Z-])\w+/g", that returns
"This" "-Part" "-I" "-Need" "-To" "-Get" "F1ST2", but I don`t need "F1ST2".
How should I do it?
It might depend on URL format, but at this point:
var url = 'https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/';
console.log(url.split('/')[4])
Try this regex
/([A-Z][a-z]|-[A-Z]|-[A-Z][a-z]-|-[A-Z]-)\w+/g
Here is a SNIPPET
var url = 'https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/';
console.log(url.match(/([A-Z][a-z]|-[A-Z]|-[A-Z][a-z]-|-[A-Z]-)\w+/g).join(''))
As #MichałSałaciński said, you should consider using split function.
BTW, if you wan't to use regular expressions, then this one will work if url format does not change : [^\/]+(?=(?:\/\w+){2}\/)
Demo
var re = /[^\/]+(?=(?:\/\w+){2}\/)/
var url = "https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/"
if(re.test(url)) {
// URL match regex pattern, we can safely get full match
var value = re.exec(url)[0];
console.log(value);
}
Explanation
[^\/]+ Any character but a slash n times
(?=...) Followed by
(?:\/\w+){2}\/ a slash and any word character (2 times) then a slash
Solution 2
This one also works using captured group 1: :\/\/[^\/]+\/[^\/]+\/([^\/]+)
Demo
var re = /:\/\/[^\/]+\/[^\/]+\/([^\/]+)/;
var url = "https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/";
if(re.test(url)) {
// URL match regex pattern, we can safely get group 1 value
var value = re.exec(url)[1];
console.log(value );
}

How to find in javascript with regular expression string from url?

Good evening, How can I find in javascript with regular expression string from url address for example i have url: http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/ and I need only string between last slashes (/ /) http://something.cz/something/string/ in this example word that i need is mikronebulizer. Thank you very much for you help.
You could use a regex match with a group.
Use this:
/([\w\-]+)\/$/.exec("http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/")[1];
Here's a jsfiddle showing it in action
This part: ([\w\-]+)
Means at least 1 or more of the set of alphanumeric, underscore and hyphen and use it as the first match group.
Followed by a /
And then finally the: $
Which means the line should end with this
The .exec() returns an array where the first value is the full match (IE: "mikronebulizer/") and then each match group after that.
So .exec()[1] returns your value: mikronebulizer
Simply:
url.match(/([^\/]*)\/$/);
Should do it.
If you want to match (optionally) without a trailing slash, use:
url.match(/([^\/]*)\/?$/);
See it in action here: http://regex101.com/r/cL3qG3
If you have the url provided, then you can do it this way:
var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/';
var urlsplit = url.split('/');
var urlEnd = urlsplit[urlsplit.length- (urlsplit[urlsplit.length-1] == '' ? 2 : 1)];
This will match either everything after the last slash, if there's any content there, and otherwise, it will match the part between the second-last and the last slash.
Something else to consider - yes a pure RegEx approach might be easier (heck, and faster), but I wanted to include this simply to point out window.location.pathName.
function getLast(){
// Strip trailing slash if present
var path = window.location.pathname.replace(/\/$?/, '');
return path.split('/').pop();
}
Alternatively you could get using split:
var pieces = "http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/".split("/");
var lastSegment = pieces[pieces.length - 2];
// lastSegment == mikronebulizer
var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/';
if (url.slice(-1)=="/") {
url = url.substr(0,url.length-1);
}
var lastSegment = url.split('/').pop();
document.write(lastSegment+"<br>");

Put the filename and the filetype in a array

I want to put the filename and the filetype in a array and I know the answer (split) but I don't know how to look for the last dot before the extension begin.
Examples: Funny - SMS 02.jpg will get Funny - SMS 02in one array and jpg in another. But when I'm try to split the name of an file that already contains dots, the trouble begins. Funny - When you see it....jpg prints Funny - When you see it in for example fname[0] and jpg in fname[1].
How can I make it print Funny - When you see it... as fname[0] and jpg as fname[1]?
Thanks in advance.
function getFnameExt(filename) {
var parts = filename.split('.'), ext = parts.pop(), fname = parts.join('.');
return [ fname, ext ];
}
console.log( getFnameExt("Funny - When you see it....jpg") );
var array = [];
var s = "Funny - When you see it....jpg";
var lastDot = s.lastIndexOf(".");
array[0] = s.substring(0, lastDot);
array[1] = s.substring(lastDot + 1);
alert(array[0] + "---" + array[1]);
For these kinds of tasks splitting is usually cumbersome. Regular expressions are more powerful:
var matches = /^(.*)\.([^.]*)$/g.exec("Funny - When you see it....jpg");
matches.shift();
// matches:
// ["Funny - When you see it...", "jpg"]
This matches the string against the regexp, which results in an array with three elements. The first is the full match which is not needed, so shift it.
^ begin of string
.* any amount of any character
\. a dot
[^.]* any amount of any character except a dot
$ end of string
With the begin/end of string anchors, .* must contain all characters before the last dot.
( and ) denote a group, which adds the matched substring to the array.
fname = "Funny - When you see it....jpg"
parts = fname.split(/\.(?=[^.]*$)/)
// parts=["Funny - When you see it...", "jpg"]
?= is called 'lookahead' and basically means "followed by". So, the above reads: "split by a dot if there's no dots after it".

Javascript (node) regex doesn't seem to match start of string

im struggling with regular expressions in Javascript, they don't seem to start at the beginning of the string. In a simple example bellow I want to get the file name and then everything after the first colon
//string
file.text:16: lots of random text here with goes on for ages
//regex
(.?)[:](.*)
// group 1 returns 't'
/^([^:]+):(.*)/.exec('file.text:16: lots of random text here with goes on for ages')
gives ....
["file.text:16: lots of random text here with goes on for ages", "file.text", "16: lots of random text here with goes on for ages"]
Try this regex:
/^([^:]+)[:](.*)/
Explaination:
^ #Start of string
( #Start of capturing class #1
[^:] #Any character other than :
+ #One or more of the previous character class
) #End of capturing class #1
[:] #One :
(.*) #Any number of characters other than newline
The ? operator captures zero or one of the previous symbol only.
You could also use string operations instead:
str = "file.text:16:";
var n = str.indexOf(":");
var fileName = str.substr(0, n);
var everythingElse = str.substr(n);
The ? operator returns 0 or 1 matches. You want the * operator, and you should select everything that isn't a : in the first set
([^:]*)[:](.*)
Non-regexy answer:
var a = s.split(":");
Then join a[1] and remaining elements.
Or just get the index of the first semicolon and create two strings using that.

Categories

Resources