简体   繁体   中英

Nodejs readFileSync regex tag between two strings

I'm trying to fetch file contents with help of nodejs fs.readFileSync() function into string like this:

let fileData = fs.readFileSync('./path, 'utf8');

after this I want to get the contents between two string through regex :

I've a string something like this:

<route-meta>
    {
        "requiresAuth": true
    }
</route-meta>

<template>

</template>

<script>
    export default {
        name: "check"
    }
</script>

<style scoped>

</style>

I need to find text/string between <route-meta> and </route-meta> so that the result should be:

{
   "requiresAuth": true
}

I tried doing this with fileData.match(/<route-meta>(.*?)<\/route-meta>/); but somehow it is giving me null result

I followed through this example: Regex match text between tags

Also I tried to check fileData.replace('route-meta', ''); but still it is giving me no desired result I mean I'm unable to do any string operations with fileData .

Guide me where I'm doing mistake.

Please don't use regex for XML parsing

But to answer your question, you can try this

let re = /<route-meta>[\s\S]*?<\/route-meta>/
let re1 = /<(\/*)route-meta>/gi
let newstr = fileData.match(re)[0].replace(re1,"")
console.log(newstr)

re finds the full set tag with content using match
re1 deletes the opening and closing tag using replace

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