I have a php function that executes inside an add_meta_box() in the WP content editor (see below) that I would like to convert to javascript so that it executes on a button click (on demand vs automatic on load) to convert the post content in real time (without posting to the server).
Is there an equivalent method set 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);
}
// the callback function
function doReplace($matches)
{
static $count = 0;
switch($count++)
{
case 0: return '<b>'.$matches[1].'</b>'; // 1st instance, wrap in bold
case 1: return '<em>'.$matches[1].'</em>'; // 2nd instance, wrap in italics
case 2: return '<u>'.$matches[1].'</u>'; // 3rd instance, wrap in underline
default: return $matches[1]; // don't change others.
}
}
Hi @Scott B:
This is really more of a StackOverflow question than a WordPress Answers question. I’ll take a stab at it but if this is not what you need I’d suggest deleting your question here and putting it up at SO.
The
Replace()
function in Javascript can take a function as an argument. Ben Nadel (who is a bonafide jQuery/Javascript rockstar, at least in my book) has a great article covering how to useReplace()
with a callback (look for the subhead “Javascript String Replace() – Function Replace”):