2016-03-05 73 views
0

有人可以幫助我一個jQuery腳本,重新格式化單詞輸入到文本框中,客戶點擊提交按鈕後。該腳本將查看輸入到文本框中的單詞,測試是否有數字值爲11個字符,然後通過在數字數據的每個3個字符後面添加空格來重新格式化數字數據,例如「我們邀請您參加特別活動在Fred街12號舉行的商務會議,欲瞭解更多信息,請致電02341123333「這應該改爲」我們正在邀請您參加在弗雷德街12號的Tueday的特別商務會議,欲瞭解更多信息,請致電023 411 233 33「謝謝jquery重新格式化文本框的內容

function Confirm() { 

var data = $('#fix').val(); 

//check if numeric and 11 numbers 
if (!isNaN(data) == true && data.length == 11) { 

//show popup, if yes run the format function 
if (window.confirm("Message contains numeric characters which might make the message not delivered to some networks. Do you want us to reformat the message ?. This might increase the numbers of pages of the message and the cost?")) { 
    format(data); 
} 
} else { 
alert('Check number format'); 
} 
} 

function format(data) { 

var first = data.substring(0, 4); 
var second = data.substring(4, 20); 
second = second.replace(/(.{3})/g, "$1 ") 

$('#fix').val("This is my mobile number " + first + " " + second); 

}; 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<input type="textbox" id="fix" name="fix" /> 
<button ID="button1" OnClick="Confirm();" runat="server">Confirm</button> 
+0

你的代碼到目前爲止是什麼樣的? – Yass

+0

我已經發布了我目前的代碼,但它沒有做到確切的工作。如果文本框的內容只是數字,它就可以工作。我需要一個腳本,在文本框包含單詞和數字的情況下工作。並且單詞中的數字應該重新格式化,並將結果返回到文本框 – Pope

回答

1

這裏你去:https://jsfiddle.net/4j7t884u/。 基本上用正則表達式查找並匹配11位數字,循環並重新格式化字符串並替換原始字符串。

var updateString = function(input_text){ 
    //1. Find consecutive 11 numeric digits 
    var match = input_text.match(/\d{11}/); 
    //2. divide it into a string of 3s separated by space 
    var new_str = ''; 
    for(var i=1;i<match[0].length+1;i++){ 
     new_str = new_str + match[0][i-1]; 
     if(i>1 && i%3 == 0) 
      new_str = new_str + ' '; 
    } 
    //3. Replace old match no. with the new one 
    input_text = input_text.replace(match[0],new_str) 
} 
+0

非常感謝您 – Pope