最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace character at specific position in textarea - Stack Overflow

programmeradmin1浏览0评论

is it posible to replace a character at a specific position within a textarea or textbox? I can work out the position using indexOf() but knowing this how can i actually replace that particular character?

is it posible to replace a character at a specific position within a textarea or textbox? I can work out the position using indexOf() but knowing this how can i actually replace that particular character?

Share Improve this question edited Apr 29, 2015 at 21:11 000 27.3k10 gold badges74 silver badges103 bronze badges asked Feb 21, 2010 at 17:04 DavidDavid 732 silver badges4 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3
<html>
<head>
<script>
function modText()
{
 var tb = document.getElementById("mtb");
 var indexToReplace = 1;
 var stringToPutIn= "!";
 var temp = tb.value;
 var startString = temp.substr(0, indexToReplace);
 var endString = temp.substring(indexToReplace+1);
 tb.value = startString+stringToPutIn+endString;
}
</script>
</head>
<body>
<input type="text" id="mtb" /><br />
<input type="button" onclick="modText();">
</body>
</html>

The replace function will NOT work because you might have the same letter ing before the letter you wish to replace.

Note the above function only works if you're replacing one and only one character.

Just use the built-in methods of JavaScript strings. Assuming you have a text area in a variable textArea:

var textArea = document.getElementById("yourTextArea");

... the following creates a nice, generic, reusable string splicing function analogous to Array's splice method that you can then use to update the textarea's value:

function spliceString(str, start, count, stringToInsert) {
  return str.slice(0, start) + stringToInsert + str.slice(start + count);
}

textArea.value = spliceString(textArea.value, charIndex, 1, "**NEW BIT**");

An alternative would be to create a splice method of all strings by augmenting String's prototype:

String.prototype.splice = function(start, count, stringToInsert) {
  return this.slice(0, start) + stringToInsert + this.slice(start + count);
};

textArea.value = textArea.value.splice(charIndex, 1, "**NEW BIT**");

You can use substr or substring to do that (notice the different semantics of the second parameter):

var str = 'foobar';
alert(str.substr(3, 3));    // bar
alert(str.substring(3, 6)); // bar

You could do something like this using replace

<input id="myTxtbox" type="textbox">

<script type="text/javascript">
    var txtbox = document.getElementByID("myTxtbox");
    document.write(txtbox.value.replace("To Replace", "With This"));
</script> 
发布评论

评论列表(0)

  1. 暂无评论