I have string like #ls/?folder_path=home/videos/
how i can find last text from string? this place is videos
other strings like
#ls/?folder_path=home/videos/
#ls/?folder_path=home/videos/test/testt/
#ls/?folder_path=seff/test/home/videos/
We could use a few more example strings, but based off of your one and only example, here's a rough regex to get you started:
.*?/\?.*?/(.*?)\//
EDIT:
Based on your extended examples:
.*?/\?.*/(.*?)\//
This regex will consume text until the second to last / and capture until the last / in the string.
This will work even if the string doesn't end in /
var str;
var re = /\w+(?=\/?$)/;
str = "#ls/?folder_path=home/videos/"
str.match(re) ; //# => videos
str = "#ls/?folder_path=home/videos/test/testt/"
str.match(re) ; //# => testt
str = "#ls/?folder_path=seff/test/home/videos/"
str.match(re) ; //# => videos
str = "#ls/?folder_path=home/videos/test/testt"
str.match(re) ; //# => testt
\/([^\/]*)\/?$
This regex will match all non / between the last two /. Where the last / is optional. The $ is matching the end of the string.
Your resulting string is then in the first capturing group (because of the ()) $1
You can test it here
There are many ways to do this. One of them:
var str = '#ls/?folder_path=home/videos/'.replace(/\/$/,'');
alert(str.substr(str.lastIndexOf('/')+1)); //=> videos
Alternative without using replace
var str = '#ls/?folder_path=home/videos/'
,str = str.substr(0,str.length-1)
,str = str.substr(str.lastIndexOf('/')+1);
alert(str); //=> videos
If your data is consistent like this string, this is a simple split based way to retreive
your required string: http://jsfiddle.net/EEkLP/
var str="#ls/?folder_path=home/videos/";
var strArr = str.split("/");
alert(strArr[strArr.length-2]);
If it always ends with / then this will works.
var str = '#ls/?folder_path=home/videos/';
var arr = str.split('/');
var index = arr.length-2;
console.log(arr[index]);
If the last word always enclosed with forward slashes, then you can try this -
".+\/([^\/]+)\/$"
or in regex notation
/.+\/([^\/]+)\/$/
Related
I have the next problem. I need to remove a part of the string before the first dot in it. I've tried to use split function:
var str = "P001.M003.PO888393";
str = str.split(".").pop();
But the result of str is "PO888393".
I need to remove only the part before the first dot. I want next result: "M003.PO888393".
Someone knows how can I do this? Thanks!
One solution that I can come up with is finding the index of the first period and then extracting the rest of the string from that index+1 using the substring method.
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.')+1);
console.log(str)
You can use split and splice function to remove the first entry and use join function to merge the other two strings again as follows:
str = str.split('.').splice(1).join('.');
Result is
M003.PO888393
var str = "P001.M003.PO888393";
str = str.split('.').splice(1).join('.');
console.log(str);
You could use a regular expression with .replace() to match everything from the start of your string up until the first dot ., and replace that with an empty string.
var str = "P001.M003.PO888393";
var res = str.replace(/^[^\.]*\./, '');
console.log(res);
Regex explanation:
^ Match the beginning of the string
[^\.]* match zero or more (*) characters that are not a . character.
\. match a . character
Using these combined matches the first characters in the string include the first ., and replaces it with an empty string ''.
calling replace on the string with regex /^\w+\./g will do it:
let re = /^\w+\./g
let result = "P001.M003.PO888393".replace(re,'')
console.log(result)
where:
\w is word character
+ means one or more times
\. literally .
many way to achieve that:
by using slice function:
let str = "P001.M003.PO888393";
str = str.slice(str.indexOf('.') + 1);
by using substring function
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.') + 1);
by using substr function
let str = "P001.M003.PO888393";
str = str.substr(str.indexOf('.') + 1);
and ...
I want to do this in node.js
example.js
var str = "a#universe.dev";
var n = str.includes("b#universe.dev");
console.log(n);
but with restriction, so it can search for that string only after the character in this example # so if the new search string would be c#universe.dev it would still find it as the same string and outputs true because it's same "domain" and what's before the character in this example everything before # would be ignored.
Hope someone can help, please
Look into String.prototype.endsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
First, you need to get the end of the first string.
var ending = "#" + str.split("#").reverse()[0];
I split your string by the # character, so that something like "abc#def#ghi" becomes the array ["abc", "def", "ghi"]. I get the last match by reversing the array and grabbing the first element, but there are multiple ways of doing this. I add the separator character back to the beginning.
Then, check whether your new string ends the same:
var n = str.endsWith(ending);
console.log(n);
var str = "a#universe.dev";
var str2 = 'c#universe.dev';
str = str.split('#');
str2 = str2.split('#');
console.log(str[1] ===str2[1]);
With split you can split string based on the # character. and then check for the element on position 1, which will always be the string after #.
Declare the function
function stringIncludeAfterCharacter(s1, s2, c) {
return s1.substr(s1.indexOf(c)) === s2.substr(s2.indexOf(c));
}
then use it
console.log(stringIncludeAfterCharacter('a#universe.dev', 'b#universe.dev', '#' ));
var str = "a#universe.dev";
var n = str.includes(str.split('#')[1]);
console.log(n);
Another way !
var str = "a#universe.dev";
var n = str.indexOf(("b#universe.dev").split('#')[1]) > -1;
console.log(n);
I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.
Can someone please help. I need to get the characters between two slashes e.g:
Car/Saloon/827365/1728374
I need to get the characters between the second and third slashes. i.e 827365
You can use the split() method of the String prototype, passing in the slash as the separator string:
const value = 'Car/Saloon/827365/1728374';
const parts = value.split('/');
// parts is now a string array, containing:
// [ "Car", "Saloon", "827365", "1728374" ]
// So you can get the requested part like this:
const interestingPart = parts[2];
It's also possible to achieve this as a one-liner:
const interestingPart = value.split('/')[2];
Documentation is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
This will simply alert 1728374, as you want
alert("Car/Saloon/827365/1728374".split('/')[3]);
or, a bit longer, but also more readable:
var str = "Car/Saloon/827365/1728374";
var exploded = str.split('/');
/**
* str[0] is Car
* str[1] is Saloon
* str[2] is 827365
* str[3] is 1728374
*/
Try the_string.split('/') - it gives you an array containing the substrings between the slashes.
try this:
var str = 'Car/Saloon/827365/1728374';
var arr = str.split('/'); // returns array, iterate through it to get the required element
Use split to divide the string in four parts:
'Car/Saloon/827365/1728374'.split('/')[2]
Gives "827365"
You will have to use the .split() function like this:
("Car/Saloon/827365/1728374").split("/")[2];
"Car/Saloon/827365/1728374".split("/")[2]
"Car/Saloon/827365/1728374".split("/")[3]
How many you want you take it.. :)
var str = "Car/Saloon/827365/1728374";
var items = str.split("/");
for (var i = 0; i < items.length; i++)
{
alert(items[i]);
}
OR
var lastItem = items[items.length - 1]; // yeilds 1728374
OR
var lastItem1728374 = items[2];
Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
Eg, if I have this string:
hello/world
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
hello/wo\/rld
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
hello
wo\/rld
test it at ideone.com
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
Here's a way adapted from the techniques in this blog post:
var str = "Testing/one\\/two\\/three";
var result = str.replace(/(\\)?\//g, function($0, $1){
return $1 ? '/' : '[****]';
}).split('[****]');
Live example
Given:
Testing/one\/two\/three
The result is:
[0]: Testing
[1]: one/two/three
That first uses the simple "fake" lookbehind to replace / with [****] and to replace \/ with /, then splits on the [****] value. (Obviously, replace [****] with anything that won't be in the string.)
/*
If you are getting your string from an ajax response or a data base query,
that is, the string has not been interpreted by javascript,
you can match character sequences that either have no slash or have escaped slashes.
If you are defining the string in a script, escape the escapes and strip them after the match.
*/
var s='hello/wor\\/ld';
s=s.match(/(([^\/]*(\\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\\/g,'')
/* returned value: (String)
hello
wor/ld
*/
Here's an example at rubular.com
For short code, you can use reverse to simulate negative lookbehind
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\\(?:\\\\)*(?:[^\\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
but to be efficient, it's probably better to split on /[/]/ and then walk the array and rejoin elements that have an escape at the end.
Something like this may take care of it for you.
var str = "/hello/wo\\/rld/";
var split = str.replace(/^\/|\\?\/|\/$/g, function(match) {
if (match.indexOf('\\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);