1

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]]
5
  • So it is a regular expression..... Commented Jan 30, 2018 at 3:38
  • Can’t you just use an array of DOM nodes? Or use a data-num attribute, then select by document.querySelector(`[data-num='${num}']`)? Commented Jan 30, 2018 at 3:43
  • not applicable, I need to update or change or remove the entire thing if need be. Commented Jan 30, 2018 at 3:52
  • Why not Xufox's suggestion, except use a <span> wrapper with the data-num as its id? Otherwise, it might help if you be more specific in your question. Commented Jan 30, 2018 at 3:55
  • I updated the description Commented Jan 30, 2018 at 3:58

1 Answer 1

1

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">"
Sign up to request clarification or add additional context in comments.

3 Comments

thanks it works, is there a way to make this to update the content inside?
You'll need to have a different function that takes a third argument of a replacement string, and returns something like: str.substring(0, str.indexOf(startlabel))+replacement+str.substring(str.indexOf('[{'+num+']]'), str.length-1)
Did it like you said but updated. str.substring(0, str.indexOf(startLabel))+startLabel+replacement+str.substring(str.indexOf('[{'+num+']]'), str.length-1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.