user824624
user824624

Reputation: 8080

extract the string between tag not working in regex

This is my vue code

<template> 

<a href="#" class="block relative">
    <img alt="profil" src="https://www.tailwind-kit.com/images/person/1.jpg" class="mx-auto object-cover rounded-full h-16 w-16 "/>
</a>

</template> 
<script> 
export default 
 { 
 name: 'code' , 
 data() { return {} } , 
 created(){}, 
 methods: {} 
  }
</ script>

now I treat this code as a whole string, i want to extract the code from "< template > ".

i tried to use regex,

function getStringBetween(str, start, end) {
    const result = str.match(new RegExp(start + "(.*)" + end));
    return result[1];
}

let test = str.match(new RegExp('<template>' + "(.*)" + '</template>'));
console.log('transferHtml',test);

but the result shows null, any other way to extract the string between certain strings ?

Upvotes: 0

Views: 73

Answers (1)

idk wut to put here
idk wut to put here

Reputation: 803

Looks like HTML. Try using an HTML parser.

var str = "CONTENT_BEFORE<template>foo</template>CONTENT_AFTER";
const parser = new DOMParser();
var parsed = parser.parseFromString(str, "text/html");
var templatetext = parsed.querySelector('template');
console.log(templatetext.innerHTML);

So in your case, it is

var str = `<template> 

<a href="#" class="block relative">
    <img alt="profil" src="https://www.tailwind-kit.com/images/person/1.jpg" class="mx-auto object-cover rounded-full h-16 w-16 "/>
</a>

</template> 
<script> 
export default 
 { 
 name: 'code' , 
 data() { return {} } , 
 created(){}, 
 methods: {} 
  }
</ script>`;
const parser = new DOMParser();
var parsed = parser.parseFromString(str, "text/html");
var templatetext = parsed.querySelector('template');
console.log(templatetext.innerHTML);

Upvotes: 1

Related Questions