2

I have a short html file loaded as a string in Nodejs.

<html>
<head>
    <title>NodeJS</title>
    <link href="/style/application.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="/scripts/script.js"></script>
    <link rel="shortcut icon" href="/favicon.ico">
  </head>
<body>
<center>
<h1><a href="#"><% title %></a></h1><br>
</center>
</body>
</html>

I need to get an array of every string between <% and %>. In this case only title.

Tried some javascript string functions and regex but can't find anything...

Maybe finding all positions of <% %> and programatically slice the strings?

2 Answers 2

2

Really regular expressions could do the trick for you:

var str = document.getElementById('template').innerHTML,
    re = /<%\s*(.*?)\s*%>/g,
    matches,
    results = [];

while((matches = re.exec(str)) !== null) {
    results.push(matches[1]);
}

console.log(results);

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

worked flawless. I have to get more into RegEx. Lot of potencial
1

If you call .split("%") on the string in question then every odd index in the array that is returned should contain your desired string as long as you don't have any instances of % on the page.

Another way to go about doing things would be to first call string.split("<%"), and then call string.split("%>") on the odd indexes if you do happen to have instances where % is an otherwise used character in your page.

Comments

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.