Is there a javascript equivalent to PHPs strtok()? In PHP, I'd use
$sub = strtok($string, ':');
(Thanks to Phil's answer for that)
However, I need to do the same in javascript.
I have a select list that contains values like this:
<select id="myFonts">
<option value='Leckerli One'>Leckerli One</option>
<option value='Lekton:regular,italic,bold'>Lekton (plus italic and bold)</option>
<option value='OFL Sorts Mill Goudy TT:regular,italic'>OFL Sorts Mill Goudy TT (plus italic)</option>
</select>
And in the jQuery change event, I need to extract the "value" field. However, if the value field contains a colon, I need to pull the string contents before the colon and return nothing after it.
For instance, in my example above, I need the values returned:
Leckerli One Lekton OFL Sorts Mill Goudy TT
Here's my jQuery currently (does not work properly when value contains the colon and additional properties):
$('#myFonts').change
(
function()
{
var myFont = $('#myFonts :selected').val();
$('#fontPreviewSrc').attr('href','http://fonts.googleapis.com/css?family='+myFont);
$('.fontPreview').attr('style','font-family:'+myFont+';font-style:normal;font-size:2em;padding-top:10px;white-space:nowrap');
}
);
PHP | strtok() for tokening string Like C strtok(), PHP strtok() is used to tokenize a string into smaller parts on the basis of given delimiters It takes input String as a argument along with delimiters (as second argument).
The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.
The strtok_r() function is thread-safe and stores its state in a user-supplied buffer instead of possibly using a static data area that may be overwritten by an unrelated call from another thread.
The strtok() function splits a string into smaller strings (tokens).
Use:
$('#myFonts :selected').val().split(':')[0]
Here's a native JavaScript solution that supports multiple chars the same way PHP strtok() does:
/**
* @param {string} s the string to search in
* @param {string} chars the chars to search for
* @param {boolean=} rtl option to parse from right to left
* @return {string}
* @example tok( 'example.com?q=value#frag', '?#' ); // 'example.com'
* @example tok( 'example.com?q=value#frag', '?#', true ); // 'frag'
*/
function tok ( s, chars, rtl ) {
var n, i = chars.length;
rtl = true === rtl;
while ( i-- ) {
n = s.indexOf(chars[i]);
s = n < 0 ? s : rtl
? s.substr(++n)
: s.substr(0, n);
}
return s;
}
Using indexOf with substr or slice was faster than using split with pop or shift. See jsperf.com/tok
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With