简体   繁体   English

通过jquery从两个单词之间的textarea中提取特定文本

[英]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".我想要一个简单的jquery代码,它可以输出“参考代码:”和“矿物”之间的文字。 So the output text should be "12345 asdf".所以输出文本应该是“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注意 textarea 有换行符和制表符

 <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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