[英]How to get substring after last specific character in JavaScript?
[英]How to get substring from string after last seen to specific characer in javascript?
我想從字符串的最后一個索引匹配空間中獲取子字符串,並將其放入另一個字符串中:
例如,如果我有: var string1="hello any body from me";
在string1中,我有4個空格,我想在string1中的最后一個空格之后得到單詞,所以在這里我想得到單詞“ me” ...我不知道string1中的空格數量...所以我如何獲得從最后一次看到的字符串到特定字符(如空格)的子字符串?
您可以使用split
方法嘗試這樣的操作,其中input
是您的字符串:
var splitted = input.split(' ');
var s = splitted[splitted.length-1];
var splitted = "hello any body from me".split(' '); var s = splitted[splitted.length-1]; console.log(s);
使用split
使其成為數組並獲取最后一個元素:
var arr = st.split(" "); // where string1 is st
var result = arr[arr.length-1];
console.log(result);
您可以使用split方法將字符串分隔為給定的分隔符“”,在這種情況下,然后獲取返回數組的最終子字符串。
如果您想使用字符串的其他部分,這是一個好方法,並且它也易於閱讀:
// setup your string var string1 = "hello any body from me"; // split your string into an array of substrings with the " " separator var splitString = string1.split(" "); // get the last substring from the array var lastSubstr = splitString[splitString.length - 1]; // this will log "me" console.log(lastSubstr); // ... // oh i now actually also need the first part of the string // i still have my splitString variable so i can use this again! // this will log "hello" console.log(splitString[0]);
如果您喜歡快速而又骯臟地編寫,那么這是一個不需要其余子字符串的好方法:
// setup your string var string1 = "hello any body from me"; // split your string into an array of substrings with the " " separator, reverse it, and then select the first substring var lastSubstr = string1.split(" ").reverse()[0]; // this will log "me" console.log(lastSubstr);
要不就 :
var string1 = "hello any body from me";
var result = string1.split(" ").reverse()[0];
console.log(result); // me
謝謝扭轉方法
我將使用正則表達式來避免數組開銷:
var string1 = "hello any body from me"; var matches = /\\s(\\S*)$/.exec(string1); if (matches) console.log(matches[1]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.