Boy
Boy

Reputation: 612

Javascript get string between two strings

I like to fetch the values between two string. this is what I am using as a placeholder to change the stuff between. so basically I appended these custom [[num}] to each tag. Im trying to make a database of it. then I am trying to make custom/predefined edits of it base on certain parameters. so basically, if there is a way to get/change/remove the things inside of the open and close strings.

<script>
var num = 14;
</script>

HTML

[[14}]<img width="50" height="50" src="//cdn.com/img5.jpg" alt="comment-image">[{14]] [[15}]<img width="50" height="50" src="//cdn.com/img6.jpg" alt="comment-image">[{15]]

Upvotes: 1

Views: 908

Answers (1)

sorak
sorak

Reputation: 2633

Here's a javascript function to extract the substring by label number:

function extractField(str, num) {
    var startLabel = '[['+num+'}]';
    return str.substring(str.indexOf(startLabel)+startLabel.length, str.indexOf('[{'+num+']]'));
}

It works by finding the index of the starting label, adding the length of the label string, and then extracting everything up to the ending label.

Example usage:

str='[[14}]<img width="50" height="50" src="//cdn.com/img5.jpg" alt="comment-image">[{14]] [[15}]<img width="50" height="50" src="//cdn.com/img6.jpg" alt="comment-image">[{15]]';

extractField(str, 14);
"<img width="50" height="50" src="//cdn.com/img5.jpg" alt="comment-image">"

Upvotes: 1

Related Questions