views:

29

answers:

2

I want to check a string and if it has no <br /> starting then I don't wanna do any thing
for example mysqtinr = 23435-acs
as you can see no <br /> starting but if the string has the following then I wanna parse it out

myString = <br /> some text goes here <b> Some other things </b>: just more test <b> http://website/index.php </b> on line <b> 43 </b> <br /> 1234-acd

I want to parse out everything after the last <br />

how can I do that thanks

+2  A: 
var index = myString.lastIndexOf("<br />");
if(index > 0)
    myString = myString.substring(index + "<br />".length);
Alex Reitbort
This doesn't work as the tag `<br/>` and `<br />` is valid. See http://jsfiddle.net/y38QH/
Robert
What do you mean by valid? he wants the string after last `br` tag
Alex Reitbort
I mean that if you try to parse a string that has `<br/>` your method won't find it.
Robert
The question was about `<br />` specifically. But the example can easily be expanded to support other tags/tag representaions like `<br>`, `<br/>` or `< br >`.
Alex Reitbort
The example also didn't have single or double quotes around it. My point being, parsing HTML directly with javascript functions `substr` and `indexOf` is only setting him up for future headaches.
Robert
I think the question should then be, "Is this a string?".
Dale
+1  A: 
var myregexp = /<br\s*\/>((?:(?!<br\s*\/>).)*)$/;
var match = myregexp.exec(subject);
if (match != null) {
    result = match[1];
} else {
    result = "";
}

Explanation:

<br\s*/>        # match <br /> with optional space
(               # capture the following:
 (?:            # repeat the following, but don't capture (because the outer parens do so already)
  (?!<br\s*/>)  # assert that it's impossible to match <br />
  .             # if so, match any character
 )*             # do this as many times as necessary...
)               # (end of capturing group)
$               # ...until the end of the string.

So we first try to match <br/> or <br /> etc. If that fails, the match fails. If not, then we capture every following character until the end of the string unless it's possible to match another <br/> along the way. This ensures that we are indeed matching from the last <br/> onwards. The result will be in backreference nr. 1 (which may be empty if there is nothing after the last <br/>).

Tim Pietzcker