簡體   English   中英

在最后三個字符前插入破折號

[英]Insert a dash before the last three characters

我需要能夠使用javascript或php在文本字段的最后三個字符前添加破折號。 例如,用戶輸入1dsb3rs,輸入更改為1dsb-3rs。 用戶看到更改(javascript)還是發生在服務器端(PHP)都沒有關系,我只需要更改就可以了。

我已經嘗試過此javascript代碼,但無法正常工作:

 $("#rid").html(function(i,v){
  return v.replace( /^([\w]{4})/, "$1-" );

這是我的文本框代碼:

<input class="form-control" type="text" id="rid" placeholder="Enter ID" size="15px" maxlength="10" name="rid" required value="<?php echo $rid; ?>">
String.prototype.splice = function( idx, rem, s ) {
    return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
};

String.prototype.addDash = function () {
    return this.splice( -3, 0, '-' );
};

document.getElementById('myinput').addEventListener('keyup', function (e) {
    this.value = this.value.replace(/\-/gi, '');
    if (this.value.length >= 4) {
        this.value = this.value.addDash();
    }
});

工作演示: http : //jsfiddle.net/seancannon/2xLFy/2/

要在服務器端執行此操作(假設數據是POST版本):

if (isset($_POST['rid']))
{
    $value = $_POST['rid'];
    if (strstr($value, '-') === false)//if no dash is in the $value string
        $value = substr($value, 0, -3).'-'.substr($value, -3);//get string minus last 3 chars, add dash, then add last 3 chars
}

或客戶端使用JavaScript(例如,使用change事件)

document.querySelector('#rid').addEventListener('change', function()
{
    if (this.value > 3)
        this.value = this.value.replace(/(.{3}$)/, '-$1');
}, false);

此模式用破折號代替最后3個字符,后跟那些非常相同的最后3個字符。 看到小提琴

您不能在表單控件上使用html()方法。 您需要使用val()

嘗試:

$("#rid").val(function(i,v){
  v.replace( /^([\w]{4})/, "$1-" );    

});

jQuery val()API文檔

我認為這應該適合您使用javascript。

var addDash = function(str){
    var chars = str.split("");
    chars.splice(chars.length-3,0,'-');
    return chars.join('')
}

用字符串調用此函數。

addDash('string');

輸出量

str-ing

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM