Extract string between characters at the end of a URL - javascript

I have the following example url: http://example.com/this/is/the/end/
I need to extract the last piece of the url, between the last two /
There may be characters after the last / but it's always between the last two / that I need.
This is what I'm trying, I think it's pretty close but it only returns the d of end
How can I extract the full end?
Javascript
var str = 'http://example.com/this/is/the/end/';
var string = str.substring(str.lastIndexOf("/")-1,str.lastIndexOf("/"));
Here's a fiddle

Use lastIndexOf with start from index as second parameter to extract the text between the two slashes.
var str = 'http://example.com/this/is/the/end/';
var lastIndex = str.lastIndexOf('/');
var string = str.substring(str.lastIndexOf("/", lastIndex - 1) + 1, lastIndex);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ : Get the last `/` index by starting search from `lastIndex - 1` index.
console.log(string);
You can also use string and array functions as follow.
var str = 'http://example.com/this/is/the/end/';
var string = str.split('/').slice(-2)[0];
console.log(string);
Also, regex can be used.
Regex Demo and Explanation
var str = 'http://example.com/this/is/the/end/';
var string = str.match(/\/(\w+)\/[^\/]*?$/)[1];
console.log(string);

This is a good place to use regular expressions:
Regex Live Demo
var str = 'http://example.com/this/is/the/end/';
var re = /\/([^\/]*)\/[^\/]*$/;
// \/ - look for /
// ([^\/]*) - capture zero or more characters that aren't a /
// \/ - look for last /
// [^\/]* - look for more chars that aren't /
// $ - match the end of the string
var last = re.exec(str)[1];
console.log(last); //end

You can simply split and slice
'http://example.com/this/is/the/end/'.split('/').slice(-2)[0]

Related

Need to extract values from string in Javascript between words and characters

I will be receiving the following string format from an AJAX call:
[link=https://www.w3schools.com text=here]
I need to extract the values after "link=" and the value after "text=" so, my ideal output would assign "https://www.w3schools.com" to a variable and then "here" to a variable as shown in the code below. The values for "link=" and "text=" will change.
I've tried playing around with regex matching and using .split in Javascript, but I can't get the intended values just right.
var str = "[link=https://www.w3schools.com text=here]";
var link = str.match(/link=(.*)/)[1]; //gets the link but includes rest of string
var linkText = str.match(/text=(.*)/)[1]; //gets "here" plus the closing bracket
add "\s" and "]" in your pattern, Try this
var str = "[link=https://www.w3schools.com text=here]";
var link = str.match(/link=(.*)\s/)[1]; //gets the link but includes rest of string
var linkText = str.match(/text=(.*)]/)[1];
console.log(link);
console.log(linkText);
You may use
var str = "[link=https://www.w3schools.com text=here]";
var m, res=[], rx=/(?:^|[\s[])(link|text)=([^\][\s]*)/g;
while (m = rx.exec(str)) {
console.log(m[1], "=", m[2]);
}
The regex is
/(?:^|[\s[])(link|text)=([^\][\s]*)/
See the regex demo.
Details
(?:^|[\s[]) - start of string or a whitespace or [
(link|text) - Group 1: link or text words
= - a = symbol
([^\][\s]*) - Group 2: any 0+ chars other than [, ] and whitespace.

How to replace numbers with an empty char

i need to replace phone number in string on \n new line.
My string: Jhony Jhons,jhon#gmail.com,380967574366
I tried this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /[0-9]/g;
var rec = str.trim().replace(regex, '\n').split(','); //Jhony Jhons,jhon#gmail.com,
Number replace on \n but after using e-mail extra comma is in the string need to remove it.
Finally my string should look like this:
Jhony Jhons,jhon#gmail.com\n
You can try this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var regex = /,[0-9]+/g;
str.replace(regex, '\n');
The snippet above may output what you want, i.e. Jhony Jhons,jhon#gmail.com\n
There's a lot of ways to that, and this is so easy, so try this simple answer:-
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var splitted = str.split(","); //split them by comma
splitted.pop(); //removes the last element
var rec = splitted.join() + '\n'; //join them
You need a regex to select the complete phone number and also the preceding comma. Your current regex selects each digit and replaces each one with an "\n", resulting in a lot of "\n" in the result. Also the regex does not match the comma.
Use the following regex:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /,[0-9]+$/;
// it replaces all consecutive digits with the condition at least one digit exists (the "[0-9]+" part)
// placed at the end of the string (the "$" part)
// and also the digits must be preceded by a comma (the "," part in the beginning);
// also no need for global flag (/g) because of the $ symbol (the end of the string) which can be matched only once
var rec = str.trim().replace(regex, '\n'); //the result will be this string: Jhony Jhons,jhon#gmail.com\n
var str = "Jhony Jhons,jhon#gmail.com,380967574366";
var result = str.replace(/,\d+/g,'\\n');
console.log(result)

Replace after char '-' or '/' match

I'm trying to execute regex replace after match char, example 3674802/3 or 637884-ORG
The id can become one of them, in that case, how can I use regex replace to match to remove after the match?
Input var id = 3674802/3 or 637884-ORG;
Expected Output 3674802 or 637884
You could use sbustring method to take part of string only till '/' OR '-':
var input = "3674802/3";
var output = input.substr(0, input.indexOf('/'));
var input = "637884-ORG";
var output = input.substr(0, input.indexOf('-'));
var input = "3674802/3";
if (input.indexOf('/') > -1)
{
input = input.substr(0, input.indexOf('/'));
}
console.log(input);
var input = "637884-ORG";
if (input.indexOf('-') > -1)
{
input = input.substr(0, input.indexOf('-'));
}
console.log(input);
You can use a regex with a lookahead assertion
/(\d+)(?=[/-])/g
var id = "3674802/3"
console.log((id.match(/(\d+)(?=[/-])/g) || []).pop())
id = "637884-ORG"
console.log((id.match(/(\d+)(?=[/-])/g) || []).pop())
You don't need Regex for this. Regex is far more powerful than what you need.
You get away with the String's substring and indexOf methods.
indexOf takes in a character/substring and returns an integer. The integer represents what character position the character/substring starts at.
substring takes in a starting position and ending position, and returns the new string from the start to the end.
If are having trouble getting these to work; then, feel free to ask for more clarification.
You can use the following script:
var str = '3674802/3 or 637884-ORG';
var id = str.replace(/(\d+)[-\/](?:\d+|[A-Z]+)/g, '$1');
Details concerning the regex:
(\d+) - A seuence of digits, the 1st capturing group.
[-\/] - Either a minus or a slash. Because / are regex delimiters,
it must be escaped with a backslash.
(?: - Start of a non-capturing group, a "container" for alternatives.
\d+ - First alternative - a sequence of digits.
| - Alternative separator.
[A-Z]+ - Second alternative - a sequence of letters.
) - End of the non-capturing group.
g - global option.
The expression to replace with: $1 - replace the whole finding with
the first capturing group.
Thanks To everyone who responded to my question, was really helpful to resolve my issue.
Here is My answer that I built:
var str = ['8484683*ORG','7488575/2','647658-ORG'];
for(i=0;i<str.length;i++){
var regRep = /((\/\/[^\/]+)?\/.*)|(\-.*)|(\*.*)/;
var txt = str[i].replace(regRep,"");
console.log(txt);
}

How to strip last element of dash delimited string in Javascript

I have string delimited with dashes like:
x#-ls-foobar-takemeoff-
How can I remove takemeoff- using javascript where takemeoff- can be any amount of characters ending in a dash?
var str = "x#-ls-foobar-takemeoff-";
var newStr = str.replace(/[^-]+-$/,"");
Basic regular expression says
[^-]+ <-- Match any characters that is not a dash
- <-- Match a dash character
$ <-- Match the end of a string
If you have a string str, you can do the following:
str = str.substr(0, str.lastIndexOf("-", str.length - 2));
Using substr() and lastIndexOf():
var myStr = "x#-ls-foobar-takemeoff-";
myStr = myStr.substr(0, myStr.length-1); // remove the trailing -
var lastDash = myStr.lastIndexOf('-'); // find the last -
myStr = myStr.substr(0, lastDash);
alert(myStr);
Outputs:
x#-ls-foobar
jsFiddle here.

How can I remove all characters up to and including the 3rd slash in a string?

I'm having trouble with removing all characters up to and including the 3 third slash in JavaScript. This is my string:
http://blablab/test
The result should be:
test
Does anybody know the correct solution?
To get the last item in a path, you can split the string on / and then pop():
var url = "http://blablab/test";
alert(url.split("/").pop());
//-> "test"
To specify an individual part of a path, split on / and use bracket notation to access the item:
var url = "http://blablab/test/page.php";
alert(url.split("/")[3]);
//-> "test"
Or, if you want everything after the third slash, split(), slice() and join():
var url = "http://blablab/test/page.php";
alert(url.split("/").slice(3).join("/"));
//-> "test/page.php"
var string = 'http://blablab/test'
string = string.replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'')
alert(string)
This is a regular expression. I will explain below
The regex is /[\s\S]*\//
/ is the start of the regex
Where [\s\S] means whitespace or non whitespace (anything), not to be confused with . which does not match line breaks (. is the same as [^\r\n]).
* means that we match anywhere from zero to unlimited number of [\s\S]
\/ Means match a slash character
The last / is the end of the regex
var str = "http://blablab/test";
var index = 0;
for(var i = 0; i < 3; i++){
index = str.indexOf("/",index)+1;
}
str = str.substr(index);
To make it a one liner you could make the following:
str = str.substr(str.indexOf("/",str.indexOf("/",str.indexOf("/")+1)+1)+1);
You can use split to split the string in parts and use slice to return all parts after the third slice.
var str = "http://blablab/test",
arr = str.split("/");
arr = arr.slice(3);
console.log(arr.join("/")); // "test"
// A longer string:
var str = "http://blablab/test/test"; // "test/test";
You could use a regular expression like this one:
'http://blablab/test'.match(/^(?:[^/]*\/){3}(.*)$/);
// -> ['http://blablab/test', 'test]
A string’s match method gives you either an array (of the whole match, in this case the whole input, and of any capture groups (and we want the first capture group)), or null. So, for general use you need to pull out the 1th element of the array, or null if a match wasn’t found:
var input = 'http://blablab/test',
re = /^(?:[^/]*\/){3}(.*)$/,
match = input.match(re),
result = match && match[1]; // With this input, result contains "test"
let str = "http://blablab/test";
let data = new URL(str).pathname.split("/").pop();
console.log(data);

Categories

Resources