Skip to content

Instantly share code, notes, and snippets.

@zhuweiyou
Created August 18, 2023 09:47
Show Gist options
  • Save zhuweiyou/b598e19499806314807bc200223d7f41 to your computer and use it in GitHub Desktop.
Save zhuweiyou/b598e19499806314807bc200223d7f41 to your computer and use it in GitHub Desktop.
取中间文本
export function getMiddleString(src = '', left = '', right = '', more = false) {
let leftIndex = src.indexOf(left)
if (leftIndex === -1) {
return ''
}
leftIndex += left.length
let rightIndex
if (more) {
rightIndex = src.lastIndexOf(right, leftIndex)
} else {
rightIndex = src.indexOf(right, leftIndex)
}
if (rightIndex === -1) {
return ''
}
return src.slice(leftIndex, rightIndex)
}
import { getMiddleString } from './get-middle-string.js'
// get middle
getMiddleString('[hello][world]', '[', ']') // hello
// get more middle
getMiddleString('[hello][world]', '[', ']', true) // hello][world
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment