+ 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.
9 Respostas
+ 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);
+ 13
string.match(/\/.*?(?=\.html?)$/gmi)[0].replace(/^\//gmi, '')
//use regexes for hard situations
+ 3
You could use:
.slice()
.search()
.split()
Google these and see which one suits you best
+ 3
You could also use indexOf().
https://www.w3schools.com/jsref/jsref_indexof.asp
+ 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);
+ 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);
+ 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✌
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
- 2
ValentinHacker Never ever use Regex if you can avoid it. You can solve this problem here using simply lastIndexOf.