0

I need to search a <div> of a specific class for a simple text system, then store the text.

Basically, there will be a div, and inside the div there might be some text like:

[ALERT](TEXT TO STORE HERE)

I'd like to search a div for the ALERT tag, then store any text inside the () under a variable if it exists, and push an alert to the console if it's found.

However, while I can easily find the first part, [ALERT], I cannot figure out how to find the whole string, or store the containing text. I think it should end up something like:

var alerttext = $("#result").find("[ALERT](.)")=(function()
{
return $(this).html();
}).get();

However, that seems pretty far off, and definitely isn't working.

Edit: The html would resemble:

<div id="bbb" class=""><p id="aaa">text test text

[ALERT](TEXT TO STORE HERE)

More text down here

</p></div>
1
  • Can you include html at Question ? Commented Feb 26, 2016 at 22:03

1 Answer 1

2

Try using .text() , String.prototype.replace() with RegExp /(\n.+\()|(\).+\n+\s+$)/g to replace input string up to ( , from ) to end of input , remove newline, space characters at beginning and end of matched string

var arr = [];

$("#bbb").text(function(i, text) {
  if (text.indexOf("[ALERT]") >= 0) {
    var match = text.replace(/(\n.+\()|(\).+\n+\s+$)/g, "");
    arr.push(match);
    console.log(arr);
  };
  return text
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="bbb" class="">
  <p id="aaa">text test text [ALERT](TEXT TO STORE HERE) More text down here
  </p>
</div>

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

1 Comment

This works perfectly- I should have known it was gonna come down to regex. Thanks for your help!

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.