最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Insert a specific character into a stringarray - Stack Overflow

programmeradmin3浏览0评论

I need to add - into the output on the screen for the ID. I keep messing up the splice or subString. I am not just if I am doing this right. This is my first post.

Basically I need to turn the output from 00164973 to 001-64-973

function getID()
{
      studentID = prompt("Please enter your student ID. \nExample: 01234567 ","00164973");
      if(studentID.length == 8)
      {
         document.write("Student ID: <strong>" +studentID+ "</strong><br />");
         getFName();
      }
      else
      {
         document.write("I'm sorry but <strong>" +studentID+ "</strong> is not a valid ID. <br />Please try again.<br />");
         getID();
      }
} /*End of getID() */

I need to add - into the output on the screen for the ID. I keep messing up the splice or subString. I am not just if I am doing this right. This is my first post.

Basically I need to turn the output from 00164973 to 001-64-973

function getID()
{
      studentID = prompt("Please enter your student ID. \nExample: 01234567 ","00164973");
      if(studentID.length == 8)
      {
         document.write("Student ID: <strong>" +studentID+ "</strong><br />");
         getFName();
      }
      else
      {
         document.write("I'm sorry but <strong>" +studentID+ "</strong> is not a valid ID. <br />Please try again.<br />");
         getID();
      }
} /*End of getID() */
Share Improve this question edited Nov 9, 2014 at 18:24 Rahil Wazir 10.1k11 gold badges45 silver badges65 bronze badges asked Nov 9, 2014 at 18:20 Taylor MackTaylor Mack 411 gold badge1 silver badge8 bronze badges 1
  • What does the code look like right now? – Bert Commented Nov 9, 2014 at 18:28
Add a ment  | 

2 Answers 2

Reset to default 4

I would suggest just using a regular expression and replace to edit the number. Since you know the length of the ID and where the breaks should occur this will work

studentID = studentID.replace(/(\w{3})(\w{2})(\w{3})/, '$1-$2-$3');

It will handle any word characters so it will work with letters or numbers.

If you wanted to go with slice you can try like below

var id = "00164973";
var first = id.slice(0,3);
var middle = id.slice(3,5);
var last = id.slice(5,8);
var delimeter = "-";
var result = first+delimeter+middle+delimeter+last;
alert(result);

This might be more line of code. But this is clean and easy to understand. Jsfiddle

发布评论

评论列表(0)

  1. 暂无评论