Getting last segment of url [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to extract the last segment of URLs like this:
localhost:15043/Maintenance/ModelDetails/3?makeId=14
and this:
//localhost:15043/Maintenance/ModelDetails/3
I used below code, but this code does not work in this link:
localhost:15043/Maintenance/ModelDetails/3?makeId=14
var last_segment = window.location.hash.split('/').pop();

You can use the pathname, search, and/or hash part of the window.location to do this. Ignore the parser here as it is just used as an example to run this code.
var url = "http://localhost:15043/Maintenance/ModelDetails/3?blah=abc&makeId=14#test";
function parseUrl(url) {
var a = document.createElement("a");
a.href = url;
return a;
}
var parser = parseUrl(url);
var last_segment = parser.pathname.split('/').pop();
var searchParams = parser.search.substring(1).split("&");
var lastParamValue = searchParams[searchParams.length-1].split("=")[1];
var hash = parser.hash;
console.log(last_segment);
console.log(lastParamValue);
console.log(hash);

Won't this simple regex .+\/ work for you with replace() ?
var getLastSegment = function(url) {
return url.replace(/.+\//, '');
};
console.log(getLastSegment("localhost:15043/Maintenance/ModelDetails/3?makeId=14"));
console.log(getLastSegment("//localhost:15043/Maintenance/ModelDetails/3"));

You can use a regexp in your .split() method.
const pattern1 = /\?|\/|\&/;
const pattern2 = /\//;
const str = 'localhost:15043/Maintenance/ModelDetails/3?makeId=14';
console.log(str.split(pattern1).pop()); // return 'makeId=14'
console.log(str.split(pattern2).pop()); // return '3?makeId=14'
The pattern1 will split the url on the ?, / and & characters, and pattern2 only on / character. So you can adjust the regexp to match with what you want.

Related

Extracting a string from another string Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have this particular string :
TOYIN KEMIOGS/OYO/2277TGOGSLAGOS
from this string containing 2 '/'
I want it to extract from wherever we have OGS and stop at wherever we have OGS. OGS always start and end my extracted string
I want an extracted result like this
OGS/OYO/2277TGOGS
Thanks so much
You can achieve it but as a string between first occurrence and last occurrence of OGS as follows:
var a = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
console.log(a.slice(a.indexOf("OGS"),a.lastIndexOf("OGS")) +"OGS");
You can use match method of string to extract the data required.
const str = "TOYIN KEMIOGS/OYO/2277TGOGSLAGOS";
const result = str.match(/OGS.*OGS/); // Its greedy in nature so you can also use /OGS.*?OGS/
console.log(result[0]);
let str = "TOYIN KEMIOGS/OYO/2277TGOGSLAGOS";
let phrase = "OGS";
let start = str.indexOf(phrase);
let end = str.lastIndexOf(phrase) + phrase.length;
let newStr = str.slice(start, end);
console.log(newStr);
You can treat the start/stop sequences as non-matching groups:
const str = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
const [match] = str.match(/(?:OGS).+(?:OGS)/);
console.log(match); // "OGS/OYO/2277TGOGS"
If you don't want to keep the start/stop sequences ("OGS"), you can treat them as positive lookbehind/lookaheads:
const str = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
const [match] = str.match(/(?<=OGS).+(?=OGS)/);
console.log(match); // "/OYO/2277TG"
Here is a string manipulation version, which captures the first and last index.
const extractBetween = (str, marker) =>
str.slice(str.indexOf(marker),
str.lastIndexOf(marker) + marker.length);
const str = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
const match = extractBetween(str, 'OGS');
console.log(match); // "OGS/OYO/2277TGOGS"

Remove word before the slash with jquery [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
How to remove word before slash using jquery?
/bis/admin
In my case, I want to remove "bis". any help?
You can use the JavaScript split method
var text = "/bis/admin";
var result = text.split("/");
console.log(result[result.length - 1]);
Another example
var text = "/bis/admin/dashboard";
var result = text.split("/");
console.log(result[result.length - 1]);
You could do the following using a regular expression
var el = '/bis/admin';
var newEl = el.replace(/^.*\//, "");
newEl will be 'admin'
You can just do:
let myString = '/bis/admin';
myString.split('/')[myString.split('/').length-1];
var str = "/bis/admin";
var splitStr = str.split("/");
var out = "/" + n[n.length - 1] //Out contains /admin
split string with /.
var strn = "/bis/admin";
console.log(strn.split("/")[2]);
Or you can simply use regex
var strn = "/bis/admin";
console.log(strn.replace(/^\/([^/]*)\//,""));

How can I do string replace in jquery [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
I have this code
$("#title").keyup(function(){
var titleval = $("#title").val();
var res = titleval.replace(" ", "-");
$("#newsurl").val(res);
});
to replace spaces into dash to get URL like this
wordone-wordtow-wordthree
but i have problem with this code it's just replace first space like this
wordone-wordtow wordthree
How can i solve this problem
You need to do a global match, you can do this with a regex
var res = titleval.replace(/\s/g, "-");
Though String.prototype.replace does support having flags passed, this is deprecated in firefox and already doesn't work in chrome/v8.
Alternate method (if regex is not mandatory) could be to split and join
var res = titleval.split(" ").join("-");
or
var res = titleval.split(/\s+/).join("-");
Use regex with global flag
titleval.replace(/\s/g, "-");
try like this:
$("#title").keyup(function(){
var titleval = $("#title").val();
var res = titleval.replace(/\s+/g, '-');
$("#newsurl").val(res);
});

Regular expression for remove last n characters [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have a requirement to remove last n characters from string or remove 'page' from a particular string.
Eg:
var string = 'facebookpage';
Expected output string = 'facebook'
I would like to remove 'page' from the string.
Done it using substring.
var str = "facebookpage";
str = str.substring(0, str.length - 4);
Could you help me to find some better way to do it.
Regex for this:
//str - string;
//n - count of symbols, for return
function(str, n){
var re = new RegExp(".{" + n + "}","i");
return str.match(re);
};
EDIT:
For remove last n characters:
var re = new RegExp(".{" + n + "}$","i");
return str.replace(re, "");
UPDATE:
But use regex for this task, not good way; For example, AVG Runtime for 100000 iterations:
Str length solution = 63.34 ms
Regex solution = 172.2 ms
Use javascript replace function
var str = "facebookpage";
str = str.replace('page','');
You can use this regular expression :
(.*)\\w{4}
code :
var regex =(new RegExp("(.*)\\w{4}"))
val output = regex .exec("facebookpage")
// output is : ["facebookpage", "facebook"]
// output[1] is the Expected output which you want.
Hope this helps.

Extract a part of a string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I need to extract a part of a string. My goal is to extract from this string:
217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email
the content between utmcsr= and |
So the output would be : "search_email_alerts".
var str = "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email";
var newStr1 = str.split("utmcsr=");
var newStr2 = newStr1[1].split("|");
var extractedStr = newStr2[0];
The variable extractedStr will be "search_email_alerts".
Use regular expression like following:
var test = "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email";
var result = test.match("/utmcsr=([^|]*)\|/");
alert(result[1]); // result[1] is your desired string
var str = "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email";
match = str.match(/utmcsr=(.*?)\|/);
output = match[1];
var str = "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email"
var result = str.substring(str.indexOf("utmcsr=") + 7,str.indexOf("|"))
Result contains the desired text.
You can do that in two ways
substring
match
Here's how you can do it with regex:
var str= "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email";
var res = str.match(/^.*utmcsr=(.*)\|.*\|.*$/);
res[1]
Here you go -
var str = "217591953.1396968335.2.2.utmcsr=search_email_alerts|utmccn=(not set)|utmcmd=email";
var startIndex = str.indexOf("utmcsr=") + "utmcsr=".length;
var numOfCharsToExtract = str.indexOf("|") - startIndex;
var result = str.substring(startIndex, numOfCharsToExtract);

Categories

Resources