JavaScript ha un equivalente a preg_replace_callback di PHP?

29 ott 2010, 04:57:16
Visualizzazioni: 671
Voti: 3

Ho una funzione php che viene eseguita all'interno di un add_meta_box() nell'editor di contenuti di WP (vedi sotto) che vorrei convertire in javascript in modo che venga eseguita al click di un pulsante (on demand invece che automaticamente al caricamento) per convertire il contenuto del post in tempo reale (senza inviare al server).

Esiste un metodo equivalente in javascript?

add_meta_box('mycontentfilter', __('My Content Filter'), 'my_content_filter', 'post', 'side', 'high'); 

function my_content_filter()
{
    global $post;
    $mykeyword = 'find this phrase';
    $post->post_content = preg_replace_callback("/\b($mykeyword)\b/","doReplace", $post->post_content);
}


// la funzione di callback
function doReplace($matches)
{
    static $count = 0;
    switch($count++) 
    {
        case 0: return '<b>'.$matches[1].'</b>';   // 1a occorrenza, avvolgi in grassetto
        case 1: return '<em>'.$matches[1].'</em>'; // 2a occorrenza, avvolgi in corsivo
        case 2: return '<u>'.$matches[1].'</u>'; // 3a occorrenza, avvolgi in sottolineato
        default: return $matches[1];              // non modificare le altre
    }
}
1
Commenti

Niente di personale, ma ho votato per chiudere perché questo è effettivamente legato a Javascript in generale, non a WordPress. Stack Overflow ha molte domande su questo argomento. Se non sei d'accordo, partecipa alla discussione su Meta!

Jan Fabry Jan Fabry
29 ott 2010 15:07:28
Tutte le risposte alla domanda 1
1

Ciao @Scott B:

Questa è più una domanda per StackOverflow che per WordPress Answers. Proverò a risponderti, ma se non è quello che ti serve ti suggerirei di cancellare la tua domanda qui e pubblicarla su SO.

La funzione Replace() in Javascript può accettare una funzione come argomento. Ben Nadel (che è un vero asso di jQuery/Javascript, almeno secondo me) ha un ottimo articolo che spiega come usare Replace() con una callback (cerca il sottotitolo "Javascript String Replace() - Function Replace"):

29 ott 2010 13:48:56
Commenti

Esempio: "how now, brown cow".replace(/(o)(.)/g, function(match, first, next){ return first + next.toUpperCase(); }); // restituisce "hoW noW, broWn coW"

User User
29 ott 2010 16:10:25