简体   繁体   English

仅从输入值中的粘贴值中获取第一个字符串

[英]Taking only first string from paste value in input value

I want to get only the first value from copy-paste value.我只想从复制粘贴值中获取第一个值。

For example: my copy text is: Lorem Lipsum Test例如:我的文案是: Lorem Lipsum Test

So when i copied this above text and paste into html input filed there need to come only "Lorem" i dont need other text所以当我复制上面的文本并粘贴到 html 输入文件中时,只需要“Lorem”,我不需要其他文本

Is there any way to achieve these things?有没有办法实现这些事情?

Thanks in advance提前致谢

You can add an input event to see what you are trying to add to your element.您可以添加一个输入事件来查看您要添加到元素中的内容。 This code will split your pasted text and only add the first word.此代码将拆分您粘贴的文本并仅添加第一个单词。

 const input = document.querySelector('input'); const log = document.getElementById('values'); input.addEventListener('input', updateValue); var previousValue = ""; function updateValue(e) { log.textContent = e.data; if (e.data && e.inputType == "insertFromPaste") { if (e.data.length > 1) { let val = e.data.split(" ")[0]; let str = previousValue + val; e.target.value = str; } } previousValue = e.target.value; }
 <input placeholder="Enter some text" name="name"/> <p id="values"></p>

it only returns always the first word from string input and you have to clear for copy new value then it's show first word of the new copied string.它始终只返回字符串输入中的第一个单词,您必须清除复制新值,然后显示新复制字符串的第一个单词。

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#getfirstword").on("keyup", function(e) { debugger // do stuff! var str = $(this).val(); //Now i separate them by "|" var str1 = str.split('|'); //Now i want to get the first word of every split-ed sting parts: var firstWord =""; for (var i=0;i<str1.length;i++) { //What to do here to get the first word :) firstWord = str1[i].split(' ')[0]; } alert(firstWord); }) }); </script> </head> <body> <input id="getfirstword" /> </body> </html>

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

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