![](/img/trans.png)
[英]Javascript match a string which start with a specific char from the set of chars and end with same char using Regular Expression
[英]Delete char from input using start and end position javascript
我正在尝试通过以下方式从输入中删除文本,但该文本在Mozilla中不起作用,有人可以帮忙吗?
在IE中正常工作。
var start = txt.selectionStart;
var end = txt.selectionEnd;
var selectedStr = txt.value.toString().substring(start, end);
txt.value = txt.value.toString().replace(selectedStr, "");
Mozilla(和其他浏览器)使用document.selection
, window.getSelection()
)具有不同的实现,因此您需要根据这些方法/属性和旧版支持表来调整代码。 您可以在那里使用许多库来对其进行规范化。
这是在webkit中工作的代码示例:
var selectedStr = '';
if (window.getSelection) {
var selectedText = window.getSelection().toString()
}
似乎您正在尝试删除文本输入中的选定文本。 您将需要两种不同的方法:一种用于IE <9,另一种用于其他支持selectionStart
和selectionEnd
属性的浏览器。 这是如何做:
演示: http : //jsfiddle.net/hwG7f/1/
码:
function deleteSelected(input) {
input.focus();
if (typeof input.selectionStart == "number") {
var start = input.selectionStart,
end = input.selectionEnd,
val = input.value;
if (start != end) {
input.value = val.slice(0, start) + val.slice(end);
input.setSelectionRange(start, start);
}
} else if (typeof document.selection != "undefined") {
document.selection.createRange().text = "";
}
}
替换值不是解决此问题的正确方法。 尝试选择之前和之后的字符串块:
var start = txt.selectionStart;
var end = txt.selectionEnd;
txt.value = txt.value.substring(0,start) + txt.value.substring(end);
这是一个演示: http : //jsfiddle.net/BuMUu/1/
SelectionStart仅在IE9 +中有效。
抱歉,为什么不直接将其设置为“”。
<input type="text" id="txt" />
<input type="button" value="Clear" id="clear" />
function clear() {
var txt = document.getElementById('txt');
txt.value = "";
}
$('#clear').click(function(){clear()});
var str = "yourString"
str = str.substring(1,str.length-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.