How to extract a word from a string in Javascript. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to extract a word from a string in Javascript.

The string is "www.Desktop/hh/template.html" I wanted to extract the word template with out counting it my self but I couldn't find a way to get the last word 'e' or if there is a method. Thanks.

31st Mar 2018, 5:37 PM
Leoulg
Leoulg - avatar
9 Answers
+ 6
Or if you're wanting to always get the name of the html, php etc file no matter how deep the file is provided it is part of the URL then you can use: let myLink ="www.Desktop/hh/template.html"; let start_pos = myLink.lastIndexOf('/') + 1; let end_pos = myLink.lastIndexOf('.'); let sliced = myLink.slice(start_pos,end_pos); alert(sliced);
31st Mar 2018, 6:36 PM
ChaoticDawg
ChaoticDawg - avatar
+ 13
string.match(/\/.*?(?=\.html?)$/gmi)[0].replace(/^\//gmi, '') //use regexes for hard situations
31st Mar 2018, 7:35 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 3
You could use: .slice() .search() .split() Google these and see which one suits you best
31st Mar 2018, 5:49 PM
TurtleShell
TurtleShell - avatar
+ 3
31st Mar 2018, 5:51 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
You could do this but if the link gets any extra / or . then this will not return template: var str = myLink.split("/")[2].split(".")[0]; alert(str);
31st Mar 2018, 6:26 PM
TurtleShell
TurtleShell - avatar
+ 2
This simplifies your current code. let myLink ="www.Desktop/hh/template.html"; let word="template"; let start_pos = myLink.indexOf(word); let end_pos =start_pos + word.length; let sliced = myLink.slice(start_pos,end_pos); alert(sliced);
31st Mar 2018, 6:30 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
@chaoticdawg its simpler now and i think the 2nd one was what i wanted to do. there was a lot of confusion on mine.thanks✌
31st Mar 2018, 7:38 PM
Leoulg
Leoulg - avatar
0
Finally got it in a very messy way. I may change it to function soon. but there is probably a simpler way to do this. https://code.sololearn.com/WNMI4YD3FwuJ/?ref=app
31st Mar 2018, 6:23 PM
Leoulg
Leoulg - avatar
- 2
ValentinHacker Never ever use Regex if you can avoid it. You can solve this problem here using simply lastIndexOf.
2nd Apr 2018, 3:18 PM
Private [GER]
Private [GER] - avatar