Skip to content Skip to sidebar Skip to footer

Extracting Between Two Words From Multiline Textarea

On a create topic page I have a textarea which is filled in partially by code. Everything between the confidential tags is added by this code. There is some text in the message!

Solution 1:

Like this

var re = /{sitedetails}([\S\s]*?){\/sitedetails}/gm,
 urlRe = /Site URL:(.*)\n/var str = $(".editor").val(), newStr = re.exec(str);
newStr = newStr ? newStr[1].trim() : "";
console.log(newStr)

if (newStr) {
  var url = newStr.match(urlRe);
  if (url) url = url[1].trim();
  console.log("URL:",url)
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><textareaclass="editor"rows="10">There is some text in the message!


[confidential]
{sitedetails}

Site URL: example.com
Site Username: test
Site Password: test

FTP URL: ftp.domain.com
FTP Username: test
FTP Password: test

Optional Information: Just some text for testing purposes!

{/sitedetails}
[/confidential]</textarea>

Solution 2:

Well, for what I understand, and I may be wrong, you want to extract everything that is between Site URL: and Site Username: on the given string, and perhaps store it into a variable, then you can extract from a string this way:

sdCheck.split(/(Site URL:|Site Username:)/g)[Math.round((sdCheck.split(/(Site URL:|Site Username:)/g).length - 1) / 2)].trim();

This way you can get it. And what was done there is:

  1. Split the string in an array with a regex. this way you will always get a odd length array.

  2. Select the middle position of the array with Math.round and division.

  3. A trim to remove whitespace.

This logic will only work if there is only one Site URL: and Site Username: match in the string, but it can be transformed for other scenarios.

Snippet:

var textarea = document.getElementById('textarea'); 

extract();

functionextract() {
  var text = textarea.value;
  document.getElementById('result').innerHTML = text.split(/(Site URL:|Site Username:)/g)[Math.round((text.split(/(Site URL:|Site Username:)/g).length - 1) / 2)].trim();
}

textarea.addEventListener('keyup', function() {
  extract();
});
<textareaid="textarea"style="height: 200px; display: inline-block">
There is some text in the message!


[confidential]
{sitedetails}

Site URL: example.com
Site Username: test
Site Password: test

FTP URL: ftp.domain.com
FTP Username: test
FTP Password: test

Optional Information: Just some text for testing purposes!

{/sitedetails}
[/confidential]
</textarea><divid="result"style="display: inline-block; vertical-align: top"></div>

Post a Comment for "Extracting Between Two Words From Multiline Textarea"