-1

I have the following DOM structure:

<form>
<input type="text" id="a">
<button>Submit</button>
</form>

or:

<form>
<input type="text" id="a">
</form>

which one depends on what user have done, it's created dynamically.

I want to be able to add another input right below the previous one (it can not exist yet and be the first one). To do that, I wanna get all text until the place I'm adding new input. How can I get that text using regex?

I tried the following:

'(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]'

But it doesn't work, because it displays empty string as a result.

var afterRegex = new RegExp('(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]', 'i');
var appendAfter = $(".downloadCode textarea").val().match(afterRegex)[1];
alert(appendAfter);
Anonymous
  • 11,748
  • 6
  • 35
  • 57
khernik
  • 2,059
  • 2
  • 26
  • 51

2 Answers2

1

I'm a little confused by your code, but, based on what you've said (and that you've tagged your question with jQuery), I think that you can accomplish what you are trying to do with this code:

var $newInput = **CREATE_YOUR_NEW_INPUT_ELEMENT_HERE**;
var $form = $("form");
var $lastInput = $form.find("input:last");

// no inputs, make the new input the first element in the form
if ($lastInput.length < 1) {
    $form.prepend($newInput);
}
// at least on existing input, add the new input after the last one
else {
    $lastInput.after($newInput);
}
talemyn
  • 7,822
  • 4
  • 31
  • 52
0

You should not parse HTML using Regexp. No, seriously.

That being said, the correct syntax for multi-character alternatives is (?:alternativeA|alternativeB):

(.*?)(?:<button.*?>Submit<\/button><\/form>|<\/form>)

Note that this does not work if you have whitespace characters in between. Yet another reason not to use Regexps here.

mrks
  • 8,033
  • 1
  • 33
  • 62