Ferfa
Ferfa

Reputation: 221

How to select text between two string javascript?

I have this string:

var str = "Toto PARKER rejected the task.<br><br>Approval comments:<br>11-07-2017 20:11:29 - James EY (Comments)<br>NO!!<br><br>";

I would like a function to return "NO!!"

To do this i using:

<p>Click the button to display the array values after the split.</p>

<button onclick="myFunction()">Try it</button>   
<p id="demo"></p>

<script>
function myFunction() {
    var str = "Toto PARKER rejected the task.<br><br>Approval comments:<br>11-07-2017 20:11:29 - James EY (Comments)<br>NO!!<br><br>";
    var res = str.match("(<br\s*[\/]?>)[1](.*)(<br\s*[\/]?><br\s*[\/]?>)");
    document.getElementById("demo").innerHTML = res[0];          
}
</script>

I have some difficulties with my regex because the return is:

<br>11-07-2017 20:11:29 - James EY (Comments)<br>NO!!<br><br>

So, how to start my regex with the last <br> (to return <br>NO!!<br><br>) and after how to not return <br>?

Upvotes: 0

Views: 79

Answers (2)

Frank Wisniewski
Frank Wisniewski

Reputation: 1224

A short form...

console.log(
  str.split('<br>').filter( e => e ).pop()
);

Upvotes: 0

Mistalis
Mistalis

Reputation: 18279

Here is a solution without a regex. I splitted your string on <br>, then removed the null values, and display the last element from the result:

function myFunction() {
    var str = "Toto PARKER rejected the task.<br><br>Approval comments:<br>11-07-2017 20:11:29 - James EY (Comments)<br>NO!!<br><br>";
    var res = str.split('<br>').filter(n => n);
    document.getElementById("demo").innerHTML = res.pop();
}
<p>Click the button to display the array values after the split.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

Upvotes: 1

Related Questions