How could I just extract the text androiddev
from the following string in JavaScript?
/
I tried trimming it from the back, but I'm still stuck with the front part.
Been stuck at this for a few hours now, would really appreciate any help!
How could I just extract the text androiddev
from the following string in JavaScript?
https://www.reddit./r/androiddev/ments/49878b/droidcon_sf_is_11_days_away/
I tried trimming it from the back, but I'm still stuck with the front part.
Been stuck at this for a few hours now, would really appreciate any help!
Share Improve this question edited Jul 30, 2020 at 14:21 Penny Liu 17.6k5 gold badges86 silver badges108 bronze badges asked Mar 6, 2016 at 22:04 Dark KnightDark Knight 3071 gold badge4 silver badges18 bronze badges 7-
1
String.prototype.trim()
is available in modern browsers. – Pointy Commented Mar 6, 2016 at 22:06 - @Pointy but is that not only for when there's whitespace on both sides? – Dark Knight Commented Mar 6, 2016 at 22:07
-
var value = 'yourstring'.split('/')[4]
– Dmitriy Commented Mar 6, 2016 at 22:08 - It trims whitespace off of both sides. If there's no whitespace on one or both sides, nothing happens to that side. edit oh wait I see. You're trimming non-space stuff. Sorry, never mind. – Pointy Commented Mar 6, 2016 at 22:09
- The title of the question is misleading: PO actually asks how to get the Sub-string from the string (should it be indeed about Trimming text, then @Pointy gave exact answer). Please correct the question. Thanks and regards, – Alexander Bell Commented Mar 6, 2016 at 22:12
4 Answers
Reset to default 1var str = "https://www.reddit./r/androiddev/ments/49878b/droidcon_sf_is_11_days_away/"
var name = str.split('/')[4]
console.log(name);// androiddev
Easy and fast :)
var value = 'yourstring'.split('/')[4]
Sure you can just split the whole URL with /
, but I generally find it safer to break the URL into known parts, then extract information from those.
Here's a sort of sneaky way to do URL parsing in the browser
function parseUrl(url) {
var elem = document.createElement('a');
elem.href = url;
return {
protocol: elem.protocol,
host: elem.host,
hostname: elem.hostname,
port: elem.port,
pathname: elem.pathname,
hash: elem.hash
};
}
Then you can use it like this
var url = "https://www.reddit./r/androiddev/ments/49878b/droidcon_sf_is_11_days_away/"
parseUrl(url).pathname.split('/')[2]; // "androiddev"
Use the substr
String function:
var s = "https://www.reddit./r/androiddev/ments/49878b/droidcon_sf_is_11_days_away/";
var ss = s.substr(25, 10);
alert(ss);
Where the first argument is what index position to begin extracting at and the second is how many chars. to extract.