JS deletes everything after the last occurrence of a character

Ok i have it

var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
console.log(URL.substring(URL.lastIndexOf("/")));

Gives you "/ remove-everything-before-the-last-appearance-of-a-character"

How do I get " http://stackoverflow.com/questions/10767815/"

+4
source share
8 answers

Here you are:

var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
alert(URL.substring(0, URL.lastIndexOf("/") + 1));
Run codeHide result

Hope this helps.

+7
source
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";

console.log(URL.substring(0,URL.lastIndexOf('/')+1));
//The +1 is to add the last slash
+2
source

, ( , ):

URL.replace(/[^\/]+$/,'')

(.. /).

+1
console.log(URL.substring(0, URL.lastIndexOf("/")+1));
0

jsfiddle .

    var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
    var myRegexp = /^(.*\/)/g;
    var match = myRegexp.exec(URL);
    alert(match[1]); 
Hide result
0

,

var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
snippet.log(URL.split('/').slice(0, 5).join('/'));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script>
Hide result
0

:

var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var temp = URL.split('/');
temp.pop();
var result = temp.join('/');
alert(result);
Hide result
0

Try using .match()withRegExp /^\w+.*\d+\//

var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var res = URL.match(/^\w+.*\d+\//)[0];
document.body.textContent = res;
Run codeHide result
0
source

All Articles