簡體   English   中英

JS 刪除最后一次出現字符后的所有內容

[英]JS remove everything after the last occurrence of a character

好的,我有這個

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

給你“/remove-everything-before-the-last-occurrence-of-a-character”

我如何獲得“ http://stackoverflow.com/questions/10767815/

這個給你:

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

希望這可以幫助。

似乎是正則表達式的一個很好的例子(不敢相信還沒有人發布它):

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

刪除字符串末尾的所有連續非正斜杠字符(即最后一個 / 之后的所有內容)。

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

通用解決方案

這是一個通用函數,當在我們正在搜索的字符串(haystack)中找不到搜索到的字符或字符串(針)時,它也可以處理邊緣情況。 在這種情況下,它返回原始字符串。

 function trimStringAfter(haystack, needle) { const lastIndex = haystack.lastIndexOf(needle) return haystack.substring(0, lastIndex === -1 ? haystack.length : lastIndex + 1) } console.log(trimStringAfter('abcd/abcd/efg/ggfbf', '/')) // abcd/abcd/efg/ console.log(trimStringAfter('abcd/abcd/abcd', '/')) // abcd/abcd/ console.log(trimStringAfter('abcd/abcd/', '/')) // abcd/abcd/ console.log(trimStringAfter('abcd/abcd', '/')) // abcd/ console.log(trimStringAfter('abcd', '/')) // abcd

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

試試這個 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]);

運行這個:

 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);

嘗試使用.match()RegExp /^\\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;

嘗試基於數組的提取,如

 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.github.io/simple-snippets-console/snippet.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM