Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

regex - javascript or jquery equivalent of PHP's strtok()?

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');
    }
);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use:

$('#myFonts :selected').val().split(':')[0]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...