admin 管理员组文章数量: 1086019
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 badges4 Answers
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>
本文标签: javascriptReplace character at specific position in textareaStack Overflow
版权声明:本文标题:javascript - Replace character at specific position in textarea - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744027663a2520922.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论