簡體   English   中英

通過jquery從兩個單詞之間的textarea中提取特定文本

[英]Extracting specific text from textarea between two words via jquery

我想要一個簡單的jquery代碼,它可以輸出“參考代碼:”和“礦物”之間的文字。 所以輸出文本應該是“12345 asdf”。 請看一下我的代碼,它可以輸出“參考代碼:”之后的所有文本,但它不能僅輸出“礦物”字樣。

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

使用正則表達式

分解

/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  

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