PHP's strtok in JavaScript

Here’s what our current JavaScript equivalent to PHP's strtok looks like.

module.exports = functionstrtok (str, tokens) {
// discuss at: https://locutus.io/php/strtok/
// original by: Brett Zamir (https://brett-zamir.me)
// note 1: Use tab and newline as tokenizing characters as well
// example 1: var $string = "\t\t\t\nThis is\tan example\nstring\n"
// example 1: var $tok = strtok($string, " \n\t")
// example 1: var $b = ''
// example 1: while ($tok !== false) {$b += "Word="+$tok+"\n"; $tok = strtok(" \n\t");}
// example 1: var $result = $b
// returns 1: "Word=This\nWord=is\nWord=an\nWord=example\nWord=string\n"
const $global = (typeofwindow !== 'undefined' ? window : global)
$global.$locutus = $global.$locutus || {}
const $locutus = $global.$locutus
$locutus.php = $locutus.php || {}
if (tokens === undefined) {
tokens = str
str = $locutus.php.strtokleftOver
}
if (str.length === 0) {
returnfalse
}
if (tokens.indexOf(str.charAt(0)) !== -1) {
return strtok(str.substr(1), tokens)
}
for (var i = 0; i < str.length; i++) {
if (tokens.indexOf(str.charAt(i)) !== -1) {
break
}
}
$locutus.php.strtokleftOver = str.substr(i + 1)
return str.substring(0, i)
}
[ View on GitHub | Edit on GitHub | Source on GitHub ]

How to use

You you can install via npm install locutus and require it via require('locutus/php/strings/strtok'). You could also require the strings module in full so that you could access strings.strtok instead.

If you intend to target the browser, you can then use a module bundler such as Parcel, webpack, Browserify, or rollup.js. This can be important because Locutus allows modern JavaScript in the source files, meaning it may not work in all browsers without a build/transpile step. Locutus does transpile all functions to ES5 before publishing to npm.

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we don't consider it to be a bad thing that many of our functions are first iterations, which may still have their fair share of issues. We hope that these flaws will inspire others to come up with better ideas.

This way of working also means that we don't offer any production guarantees, and recommend to use Locutus inspiration and learning purposes only.

Notes

  • Use tab and newline as tokenizing characters as well

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1var $string = "\t\t\t\nThis is\tan example\nstring\n" var $tok = strtok($string, " \n\t") var $b = '' while ($tok !== false) {$b += "Word="+$tok+"\n"; $tok = strtok(" \n\t");} var $result = $b"Word=This\nWord=is\nWord=an\nWord=example\nWord=string\n"

« More PHP strings functions


Star