简体   繁体   中英

Extracting specific text from textarea between two words via jquery

I want a simple jquery code, which can output the text written between "Reference Code:" and "Mineral". So the output text should be "12345 asdf". Please take a look at my code which can output all the text after "Reference Code:" but it is not working output to only "Mineral" word.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <textarea class='txt' id='txt'> Name and formula Reference code: 12345 asdf Mineral name: Periclase </textarea> <h3 id="firstLine"></h3> <script> var lines = $('#txt').val().split('code:'); var outPut=lines[1]; $("#firstLine").html(outPut) </script>

Use regex

Breakdown

/code:\s+        // starts with literal code: and whitespace, here a tab
([a-zA-Z0-9-]+)  // capture alphabetics, digits and dash
\s+?Mineral/     // until the literal Mineral with a possible leading whitespace  

NOTE the textarea has newlines and tabs

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <textarea class='txt' id='txt'> Name and formula Reference code: 0N-NNN-YYYY Mineral name: Periclase Compound name: Magnesium Oxide </textarea> <h3 id="firstLine"></h3> <script> const code = $('#txt').val().match(/code:\\s+([a-zA-Z0-9-]+)\\s+?Mineral/m); $("#firstLine").html(code ? code[1] : "not found") </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM