如何使用JavaScript选择字符串的最后一个字符?

问题描述

我有一个函数可以获取用户在input中键入的字符串的最后一个字符。但是,如何使用execCommand()选择单个字符?目的是将其复制到其他input中。

我尝试了element.select(),但没有结果。

要粘贴到新input中的字符必须是原始输入中可见的字符,而不是与用户键入的键盘键相对应的字符,因为所有这些的原因是具有外部JS库在一个input中处理一些CJK字符转换,然后将结果移到另一个。.

我要使用复制粘贴方法。因此,需要选择角色。但是,如果有更好的方法可以实现,请随时告诉我。

我对Vanilla JavaScript和jQuery方法都持开放态度。

这是我的代码:

JSFiddle

function copyPaste () {
  var i1 = document.getElementById('userInput');
  var i2 = document.getElementById('input2');
  var c = i1.value.substr(lol.length - 1);
  c.select();
  document.execCommand('copy');
  i2.focus();
  document.execCommand('paste');
  i1.focus();
}
input {
  width: 255px;
}
  
button {
  display: block;
  margin: 20px 0;
  text-align: left;
}
<input type="text" id="userInput" placeholder="First,type something here.">

<button type="button" onclick="copyPaste"();>Then,click here to copy the last character<br>of the above input into the next input.</button>

<input type="text" id="input2" value="Some text...">

解决方法

您不应使用execCommand,因为它已过时。此外,您无需使用剪贴板将字符串(的一部分)传输到另一个输入框。这可以通过标准的字符串处理来完成:

  • 您可以使用slice(-1)来获取最终字符。

  • 我也希望使用addEventListener而不是onclick属性(您也有错字)。

  • 使用+=可以附加提取的字符:

var input = document.getElementById('userInput');
var output = document.getElementById('input2');
var btn = document.querySelector('button');

btn.addEventListener("click",function () {
  output.value += input.value.slice(-1);
});
input {
  width: 255px;
}
  
button {
  display: block;
  margin: 20px 0;
  text-align: left;
}
<input type="text" id="userInput" placeholder="First,type something here.">

<button type="button">Then,click here</button>

<input type="text" id="input2" value="Some text...">

,

以下内容对我有用:

html:

<input type="text" id="userInput" placeholder="First,type something here.">
<button type="button" onclick="copyPaste()";>Then,click here to copy the last character<br>of the above input into the next input.</button>
<input type="text" id="input2" value="Some text...">

js:

function copyPaste () {
  var i1 = document.getElementById('userInput');
  var i2 = document.getElementById('input2');
  var c = i1.value.slice(i1.value.length - 1);
  i2.value = c;
}

使用slice()获取字符串的最后一个字符。注意,我还修复了HTML中的onclick处理程序。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...