Rust's str::rsplit_once in TypeScript

✓ Verified: Rust 1.85
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { rsplit_once } from 'locutus/rust/str/rsplit_once'.

Or with CommonJS: const { rsplit_once } = require('locutus/rust/str/rsplit_once')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1rsplit_once('=', 'a=b=c')['a=b', 'c']
2rsplit_once('::', 'x::y::z')['x::y', 'z']
3rsplit_once(':', 'abc')null

Notes

  • Splits string on the last delimiter occurrence and returns [left, right] or null.

Here's what our current TypeScript equivalent to Rust's str::rsplit_once looks like.

export function rsplit_once(delimiter: string, str: string): [string, string] | null {
// discuss at: https://locutus.io/rust/rsplit_once/
// parity verified: Rust 1.85
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Splits string on the last delimiter occurrence and returns [left, right] or null.
// example 1: rsplit_once('=', 'a=b=c')
// returns 1: ['a=b', 'c']
// example 2: rsplit_once('::', 'x::y::z')
// returns 2: ['x::y', 'z']
// example 3: rsplit_once(':', 'abc')
// returns 3: null

const source = String(str)
const value = String(delimiter)

if (value === '') {
return [source, '']
}

const index = source.lastIndexOf(value)
if (index < 0) {
return null
}

return [source.slice(0, index), source.slice(index + value.length)]
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 23 Rust functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

  • Get inspiration from the Rust std::str docs.
  • Click "New file" in the appropriate folder on GitHub. This will fork the project to your account, directly add the file to it, and send a Pull Request to us.

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Rust str functions


Star