简体   繁体   English

Markdown 将双星号转换为 javascript 中的粗体文本

[英]Markdown to convert double asterisks to bold text in javascript

i'm trying to make my own markdown-able textarea like Stackoverflow has done.我正在尝试像 Stackoverflow 那样制作我自己的 Markdown-able textarea。 The goal is to allow people to type **blah blah** in a textarea and have the output in a div be <span style="font-weight:bold;">blah blah</span> .目标是允许人们在 textarea 中输入**blah blah**并在 div 中输出<span style="font-weight:bold;">blah blah</span>

I'm having trouble with the javascript to find and replace to the **asterisks with the HTML.我在使用 javascript 查找和替换为 HTML 的 **星号时遇到了麻烦。

here's a jsfiddle which has gotten the party started: http://jsfiddle.net/trpeters1/2LAL4/14/这是一个让派对开始的 jsfiddle: http : //jsfiddle.net/trpeters1/2LAL4/14/

here's the JS on that just to show you where I'm at:这里的 JS 只是为了向您展示我的位置:

$(document.body).on('click', 'button', function() {

var val=$('textarea').val();

var bolded=val.replace(/\**[A-z][0-9]**/gi, '<span style="font-weight:bold;">"'+val+'" </span>');

$('div').html(bolded);
});

and the HTML...和 HTML...

<textarea></textarea>
<div></div><button type="button">Markdownify</button>

any thoughts would be greatly appreciated!任何想法将不胜感激!

thanks, tim谢谢,蒂姆

The other answers fail when a char is immediately before or after the asterisks.当字符位于星号之前或之后,其他答案将失败。

This works like markdown should:这就像降价应该:

 function bold(text){ var bold = /\\*\\*(.*?)\\*\\*/gm; var html = text.replace(bold, '<strong>$1</strong>'); return html; } var result = bold('normal**bold**normal **b** n.'); document.getElementById("output").innerHTML = result;
 div { color: #aaa; } strong { color: #000; }
 <div id="output"></div>

None of the provided answers works in all cases.提供的答案都不适用于所有情况。 For example, the other solutions wont work if we have a space next to the double star, ie:例如,如果我们在双星旁边有一个空格,则其他解决方案将不起作用,即:

This will ** not ** be bold

So I wrote this:所以我写了这个:

function markuptext(text,identifier,htmltag)
{
    var array = text.split(identifier);
    var previous = "";
    var previous_i;
    for (i = 0; i < array.length; i++) {
        if (i % 2)
        {
            //odd number
        }
        else if (i!=0)
        {
            previous_i = eval(i-1);
            array[previous_i] = "<"+htmltag+">"+previous+"</"+htmltag+">";
        }
        previous = array[i];
    }
    var newtext = "";
    for (i = 0; i < array.length; i++) {
        newtext += array[i];
    }
    return newtext;
}

Just call it like this:就这样称呼它:

thetext = markuptext(thetext,"**","strong");

and it will work in all cases.它适用于所有情况。 Of course, you can also use it with other identifiers/html-tags as you like (the stackoverflow preview should have this too).当然,您也可以根据需要将它与其他标识符/html-tags 一起使用(stackoverflow 预览也应该有这个)。

Why create from scratch?为什么要从头开始创建? With so many open source editors out there, you should pick a code base you like & go from there.有这么多开源编辑器,你应该选择一个你喜欢的代码库并从那里开始。 http://oscargodson.github.com/EpicEditor/ http://markitup.jaysalvat.com/home/ http://oscargodson.github.com/EpicEditor/ http://markitup.jaysalvat.com/home/

custom component in react who receives bold like boolean反应中的自定义组件接收像布尔值一样的粗体

{(() => {
  const splitText = theText.split('**');
  return (
    <TextByScale>
      {splitText.map((text, i) => (
        <TextByScale bold={!!(i % 2)}>{text}</TextByScale>
      ))}
    </TextByScale>
  );
})()}

Choose the perfect regex that will fit your needs.选择适合您需求的完美正则表达式。 If you don't want styling to span through new line and also using ([^*<\\n]+) makes sure at least one character is in between styles or else ** without a character in-between will result will become invisible.如果您不希望样式跨越新行并使用([^*<\\n]+)确保样式之间至少有一个字符,否则**中间没有字符将导致不可见.

function format_text(text){
return text.replace(/(?:\*)([^*<\n]+)(?:\*)/g, "<strong>$1</strong>")
     .replace(/(?:_)([^_<\n]+)(?:_)/g, "<i>$1</i>")
      .replace(/(?:~)([^~<\n]+)(?:~)/g, "<s>$1</s>")
      .replace(/(?:```)([^```<\n]+)(?:```)/g, "<tt>$1</tt>")
}

•The downside to the above code is that, you can't nest styles ie *_Bold and italic_* • 上面代码的缺点是,你不能嵌套样式,即*_Bold and italic_*

To allow nested styles use this 👇允许嵌套样式使用这个👇

format_text(text){
return text.replace(/(?:\*)(?:(?!\s))((?:(?!\*|\n).)+)(?:\*)/g,'<b>$1</b>')
   .replace(/(?:_)(?:(?!\s))((?:(?!\n|_).)+)(?:_)/g,'<i>$1</i>')
   .replace(/(?:~)(?:(?!\s))((?:(?!\n|~).)+)(?:~)/g,'<s>$1</s>')
   .replace(/(?:--)(?:(?!\s))((?:(?!\n|--).)+)(?:--)/g,'<u>$1</u>')
   .replace(/(?:```)(?:(?!\s))((?:(?!\n|```).)+)(?:```)/g,'<tt>$1</tt>');

// extra:
// --For underlined text--
// ```Monospace font```
}

👆 If you want your style to span through new line, then remove \\n from the regex. 👆 如果您希望您的样式跨越新行,请从正则表达式中删除\\n Also if your new line is html break tag, you can replace \\n with <br>此外,如果您的新行是 html break 标记,则可以将\\n替换为<br>

Thank me later!晚点再谢我!

If you are using jQuery, replace this:如果您使用的是 jQuery,请将其替换为:

$(document.body).on('click', 'button', function() {

with this:有了这个:

$("button").click(function () {

The following regular expression will find your asterisk-wrapped text:以下正则表达式将查找星号包裹的文本:

/\\x2a\\x2a[A-z0-9]+\\x2a\\x2a/

I updated your fiddle as an example: http://jsfiddle.net/2LAL4/30/我更新了你的小提琴作为例子: http : //jsfiddle.net/2LAL4/30/

Your regex is broken, for one thing.一方面,您的正则表达式已损坏。 You probably want something more like:你可能想要更像:

/\*\*[A-z0-9]+\*\*/gi

The * is a special character in regular expressions. *是正则表达式中的特殊字符。 If you want to match against a literal * , then you need to escape it with \\ .如果要匹配文字* ,则需要使用\\对其进行转义。

For instance: http://jsfiddle.net/2LAL4/22/例如: http : //jsfiddle.net/2LAL4/22/

However, even with this change there's still a fair ways to go before you get to where you really want to be.然而,即使有了这种改变,在你到达你真正想去的地方之前,还有一段公平的路要走。 For instance, your example will not work if the text area contains a mix of bold and non-bold text.例如,如果文本区域包含粗体和非粗体文本,您的示例将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM