首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于重新格式化文本框内容的jquery

问用于重新格式化文本框内容的jquery
EN

Stack Overflow用户
提问于 2016-03-06 02:24:45
回答 1查看 21关注 0票数 0

有没有人能帮我写一个jquery脚本,在客户点击submit按钮后重新格式化输入到文本框中的单词。该脚本将检查键入文本框中的单词,测试是否存在11个字符的数值,然后通过在数字数据的每个3个字符之后添加空格来重新格式化数字数据。例如:“我们邀请您参加周二在弗雷德街12号举行的特别商务会议。如需更多信息,请拨打02341123333”这应改为“我们邀请您参加周二在弗雷德街12号举行的特别商务会议。

代码语言:javascript
复制
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>
EN

回答 1

Stack Overflow用户

发布于 2016-03-06 03:16:22

给你:https://jsfiddle.net/4j7t884u/。基本上,使用正则表达式查找并匹配11位数字,遍历并重新格式化字符串,并替换为原始字符串。

代码语言:javascript
复制
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)
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35817974

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档