![](/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.