[英]Split string to only return the substring prior to the nth occurrence of a delimiter in JavaScript
Java 腳本中有沒有辦法在第 n 次出現分隔符之前僅返回 substring?
例如:
如果我有一個字符串"test-123-example"
並且只想在"-"
的第二個實例之前返回 substring ,結果只是"test-123"
,有沒有辦法在一行中做到這一點?
我試過使用split()
function 使用 ( "-"
) 並使用indexOf()
找到第二個"-"
,但沒有運氣。
從上面的評論...
“像 eg ...
'test-123-example'.split('-').slice(0,2).join('-')
這樣簡單的事情怎么樣......它split
s, takes/slice
s前兩項並(重新)再次join
它們?”
console.log( 'test-123-example'.split('-').slice(0, 2).join('-') );
從上面的示例代碼中,OP 可以實現一種通用方法,以便... “在第 n 次出現定界符之前返回 substring” 。
function getSubstringPriorToNthDelimiter( value, delimiter = '-', nthCount = 2 ) { return String(value).split(String(delimiter)).slice(0, Number(nthCount)).join(String(delimiter)); } console.log( getSubstringPriorToNthDelimiter('test-123-example') ); console.log( getSubstringPriorToNthDelimiter('test_123_456_text', '_') ); console.log( getSubstringPriorToNthDelimiter('test_123_456_text', '_', 3) );
不是拆分,而是與正則表達式匹配以獲得非破折號,然后是破折號,然后是更多的非破折號。
const input = "test-123-example"; const result = input.match(/[^-]+-[^-]+/)[0]; console.log(result);
[^-]
- 除了-
之外的任何字符[^-]+
- 一個或多個不是-
的字符-
- 文字-
[^-]+
- 一個或多個不是-
的字符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.