2016-03-05 23 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