Convert BBcode to HTML using JavaScript/jQuery

百般思念 提交于 2019-11-26 21:54:41

问题


Could I please get some help with coverting some PHP code to jQuery/JavaScript? What I want is a simple BBCode to HTML converter.

Here is the PHP code. I want to achieve the same thing using jQuery/JavaScript.

$str = htmlentities($str);

// The array of regex patterns to look for
$format_search =  array(
    '#\[b\](.*?)\[/b\]#is',
    '#\[i\](.*?)\[/i\]#is',
    '#\[u\](.*?)\[/u\]#is',
);

// The matching array of strings to replace matches with
$format_replace = array(
    '<strong>$1</strong>',
    '<em>$1</em>',
    '<span style="text-decoration: underline;">$1</span>',
);

// Perform the actual conversion
$str = preg_replace($format_search, $format_replace, $str);

Thanks for your help!


回答1:


Looks ALMOST like you just need to change # to / and is to ig but I also had to change /b to \/b

Live Demo

$str = 'this is a [b]bolded[/b] and [i]italic[/i] string';

// The array of regex patterns to look for
$format_search =  [
    /\[b\](.*?)\[\/b\]/ig,
    /\[i\](.*?)\[\/i\]/ig,
    /\[u\](.*?)\[\/u\]/ig
]; // note: NO comma after the last entry

// The matching array of strings to replace matches with
$format_replace = [
    '<strong>$1</strong>',
    '<em>$1</em>',
    '<span style="text-decoration: underline;">$1</span>'
];

// Perform the actual conversion
for (var i =0;i<$format_search.length;i++) {
  $str = $str.replace($format_search[i], $format_replace[i]);
}
alert($str)

Other Live Demo

function boldFunc(str, p1, offset, s) {
  return '<strong>'+encodeURIComponent(p1)+'</strong>'
}

function italicFunc(str, p1, offset, s) {
  return '<em>'+encodeURIComponent(p1)+'</em>'
}

function underlinedFunc(str, p1, offset, s) {
  return '<span class="un">'+encodeURIComponent(p1)+'</span>'
}


$str = 'this is a [b]bölded[/b], [i]itälic[/i] and [u]ünderlined[/u] [i]strïng[/i]';

// The array of regex patterns to look for
$format_search =  [
    /\[b\](.*?)\[\/b\]/ig,
    /\[i\](.*?)\[\/i\]/ig,
    /\[u\](.*?)\[\/u\]/ig
]; // NOTE: No comma after the last entry

// The matching array of strings to replace matches with
$format_replace = [
    boldFunc,
    italicFunc,
    underlinedFunc
];

// Perform the actual conversion
for (var i =0;i<$format_search.length;i++) {
  $str = $str.replace($format_search[i], $format_replace[i]);
}
document.getElementById('output').innerHTML=$str;


来源:https://stackoverflow.com/questions/9210680/convert-bbcode-to-html-using-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!