简体   繁体   中英

How to extract only text from Markdown files in Javascript

I'm creating a simple blogging platform using Vue that serves up Markdown (*.md) files for the posts. On the main page, I want to show a list of the published posts as well as a preview of the first 30 words in each post. This is the function I have so far to show the preview ( front-matter just parses out some meta data I have at the top of of the file, and postData just contains the text from the Markdown file):

import fm from "front-matter";

function postPreview() {
  var fmData = fm(postData).body;
  var words = fmData.split(" ");
  return words.slice(0, 30).join(" ");
}

The problem is, if the Markdown has image tags or link tags, then it displays those when I just want to display the raw text. For example, if this is my Markdown file:

![alt-text...](link-to-some-picture) Here is a [link](link-to-some-website) in my file.

Then the preview should just look like this:

Here is a link in my file.

Is there some library that will let me do this?

There is probably a more direct way, but here is something that seems to work.

https://github.com/showdownjs/showdown

Here is a markdown to HTML script that works, then use jQuery to extract text() from the hidden element.

 function Markdown2HTML(sInput){ var converter = new showdown.Converter(); var html = converter.makeHtml(sInput); return html ; } function fnProcess() { var sMarkDown = $("#myInput").val(); var sHTML = Markdown2HTML(sMarkDown); $("#resultTemp").html(sHTML); $("#resultArea").html($("#resultTemp").text()); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.0/showdown.min.js"></script> <button onclick="fnProcess()">process</button> <input id="myInput" style="width:500px;" type="text" value="![alt-text...](link-to-some-picture) Here is a [link](link-to-some-website) in my file." /> <div id="resultArea" style="padding:10px;"></div> <div id="resultTemp" style="display:none"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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