Home  >  Article  >  Web Front-end  >  JavaScript code analysis to replace the last character in a string

JavaScript code analysis to replace the last character in a string

黄舟
黄舟Original
2017-03-22 14:52:341942browse

This article mainly introduces the method of JavaScript to realize the replacement of the last character in string, involving the conversion and operation of javascript strings. Friends who need it can refer to it. Next

The example in this article describes how to replace the last character in a string using JavaScript. Share it with everyone for your reference, the details are as follows:

1. Problem background

In an input box, the string length is limited to 12 digits, use the keyboard to enter a Number, the last digit in the string will be replaced, for example: 111111111111, and then enter a 3, it will display 111111111113

2. Specific implementation

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript替换字符串中最后一个字符</title>
<script type="text/javascript">
  function replaceStr()
  {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    var input_str = document.getElementById("input_str").value;
    var newStr = input_str.substring(0,11);
    if(e && e.keyCode>=48 && e.keyCode <= 57)
    {
      newStr += (e.keyCode-48);
    }
    document.getElementById("input_str").value = newStr;
  }
</script>
</head>
<body>
  <input type="text" id="input_str" maxlength="12" onkeyup="replaceStr();"/>
</body>
</html>

3. Implementation result

(1)Initialization

(2)After inputting “3”

4. Implementation method in extended appendix

jQuery:

$("#input_str").keydown(function(event){
  var nums = $("#input_str").val();
  var e = event || window.event || arguments.callee.caller.arguments[0];
  var newStr = nums.substring(0,11);
  if(e && e.keyCode>=48 && e.keyCode <= 57)
  {
    newStr += (e.keyCode-48);
  }
  $("#input_str").val(newStr);
});

The above is the detailed content of JavaScript code analysis to replace the last character in a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn