如何将用户输入的每个单词的首字母大写并打印出来?

3
我正在使用一个表单,并希望将用户输入的每个单词的首字母大写打印出来,无论他们如何输入。例如,我想要用户的"ronALd SmItH"打印为Rondald Smith。我也希望对地址和城市做同样的处理。我已经阅读了这里的所有类似问题和答案,但它们对我没有用。我不确定我是否将代码放在了错误的位置或者我做错了什么。
以下是我正在使用的代码:
    function correctFormat(customer)
    {
      var first = customer.charAt(0).toUpperCase();
      var rest = customer.substring(1).toLowerCase();
      return first + rest;
    }

我已经尝试将其放置在整个文档的各个位置,我已经尝试重命名字符串(例如名称,城市,地址)。我也阅读了其他帖子中似乎与此问题相同但都不起作用的内容。我不是输入想要大写的字符串。用户正在向表单输入数据,我需要在正确的格式中将其打印到警报中。以下是整个文档中的上述代码。很抱歉它这么长,但我又一次迷失了方向。
<html>

<!--nff Add a title to the Web Page.-->

<head>
<title>Pizza Order Form</title>
<script>

/*nff Add the doClear function to clear the information entered by the user and enter the information to be cleared when the clear entries button is clicked at the bottom of the Web Page.*/
function doClear()
{
var elements = document.getElementsByTagName('select');
elements[0].value = 'PA';

  document.PizzaForm.customer.value = "";
  document.PizzaForm.address.value = "";
  document.PizzaForm.city.value = "";
  document.PizzaForm.state.value = "";
  document.PizzaForm.zip.value = "";
  document.PizzaForm.phone.value = "";
  document.PizzaForm.email.value = "";

  document.PizzaForm.sizes[0].checked = false;
  document.PizzaForm.sizes[1].checked = false;
  document.PizzaForm.sizes[2].checked = false;
  document.PizzaForm.sizes[3].checked = false;

  document.PizzaForm.toppings[0].checked = false;
  document.PizzaForm.toppings[1].checked = false;
  document.PizzaForm.toppings[2].checked = false;
  document.PizzaForm.toppings[3].checked = false;
  document.PizzaForm.toppings[4].checked = false;
  document.PizzaForm.toppings[5].checked = false;
  document.PizzaForm.toppings[6].checked = false;
  document.PizzaForm.toppings[7].checked = false;
  document.PizzaForm.toppings[8].checked = false;
  return;
}

//nff Add a doSubmit button to indicate what the outcome will be when the user clicks the submit order button at the bottom of the form.
function doSubmit()

/*nff Add an if statement to the doSubmit function to return false if there is missing information in the text fields once the user clicks the submit order button.*/

{
  if (validateText() == false) {
    return false;
  }

//nff Add an if statement to the doSubmit function to return false if there is no pizza size selected using the radio buttons.

  if (validateRadio() == false) {
    return false;
  }

//nff Add an if statement to the doSubmit function to return false if there are no toppings selected using the checkboxes.

  if (validateCheckbox() == false) {
    return false;
  }

//nff Add an if statement to the doSubmit function to return false if the email entered by the user is empty or does not fit the acceptable format.

  if (validateEmail() == false) {
    return false;
  }

/*nff Add an if statement to the doSubmit function to return false if the phone number entered by the user is empty or does not fit the acceptable formats.*/

  if (validatePhone() == false) {
    return false;
  }

  if (validateZip() == false) {
    return false;
  }

//nff Add an alert box to show customer information from text fields when the Submit Order button is clicked.

  var customer = document.PizzaForm.customer.value;
  var address = document.PizzaForm.address.value;
  var city = document.PizzaForm.city.value;
  var state = document.PizzaForm.state.value;
  var zip = document.PizzaForm.zip.value;
  var phone = document.PizzaForm.phone.value;
  var email = document.PizzaForm.email.value;

  var size = "";
  for (var i = 0; i < document.PizzaForm.sizes.length; i++) {
    if (document.PizzaForm.sizes[i].checked) {
      size = document.PizzaForm.sizes[i].nextSibling.nodeValue.trim();
      break;
    }
  }

  var toppings = [];
  for (var i = 0; i < document.PizzaForm.toppings.length; i++) {
    if (document.PizzaForm.toppings[i].checked) {
      toppings.push(document.PizzaForm.toppings[i].nextSibling.nodeValue.trim());
    }
  }


  alert("Name: " + customer + '\n' +
    "Address: " + address + '\n' +
    "City: " + city + '\n' +
    "State: " + state + '\n' +
    "Zip: " + zip + '\n' +
    "Phone: " + phone + '\n' +
    "Email: " + email + '\n' +
    "Size: " + size + '\n' + (toppings.length ? 'Toppings: ' + toppings.join(', ') : ''));
}

//nff Add the validateText function to ensure that all text fields are complete before the order is submitted.

function validateText() {
  var customer = document.PizzaForm.customer.value;
  if (customer.length == 0) {
    alert('Name data is missing');
    document.PizzaForm.customer.focus();
    return false
  };
  var address = document.PizzaForm.address.value;
  if (address.length == 0) {
    alert('Address data is missing');
    return false;
  }
  var city = document.PizzaForm.city.value;
  if (city.length == 0) {
    alert('City data is missing');
    return false;
  }
  var state = document.PizzaForm.state.value;
  if (state.length == 0) {
    alert('State data is missing');
    return false;
  }
  var zip = document.PizzaForm.zip.value;
  if (zip.length == 0) {
    alert('Zip data is missing');
    return false;
  }
  var phone = document.PizzaForm.phone.value;
  if (phone.length == 0) {
    alert('Phone data is missing');
    return false;
  }
  var email = document.PizzaForm.email.value;
  if (email.length == 0) {
    alert('Email data is missing');
    return false;
  }
  return true;
}

//nff Add the validateRadio function so that if none of the radio buttons for pizza size are selected it will alert the user.

function validateRadio() {
  if (document.PizzaForm.sizes[0].checked) return true;
  if (document.PizzaForm.sizes[1].checked) return true;
  if (document.PizzaForm.sizes[2].checked) return true;
  if (document.PizzaForm.sizes[3].checked) return true;
  alert('Size of pizza not selected');
  document.PizzaForm.sizes[0].foucs();
  return false;
}

//nff Add the validateCheckbox function so that if none of the checkboxes for toppings are selected it will alert the user.

function validateCheckbox() {
  if (document.PizzaForm.toppings[0].checked) return true;
  if (document.PizzaForm.toppings[1].checked) return true;
  if (document.PizzaForm.toppings[2].checked) return true;
  if (document.PizzaForm.toppings[3].checked) return true;
  if (document.PizzaForm.toppings[4].checked) return true;
  if (document.PizzaForm.toppings[5].checked) return true;
  if (document.PizzaForm.toppings[6].checked) return true;
  if (document.PizzaForm.toppings[7].checked) return true;
  if (document.PizzaForm.toppings[8].checked) return true;
  alert ('Toppings are not selected');
  return false;
  }

//nff Add the validateEmail function to ensure that the email address has been entered in the correct format.

function validateEmail() {  
 if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{3,4})+$/.test(PizzaForm.email.value))  
  {  
    return (true)  
  }  
    alert("You have entered an invalid email address")  
    return (false)  
} 

//nff Add the validatePhone function to ensure that the phone number has been entered in any of the acceptable formats.

function validatePhone() {
  if (/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/.test(PizzaForm.phone.value))
  {
    return (true)
  }
    alert("You have entered an invalid phone number")
    return (false)
}
function validateZip() {
  if (/^\d{5}([\-]\d{4})?$/.test(PizzaForm.zip.value))
  {
    return (true)
  }
    alert("You have entered an invalid zip")
    return (false)
}
function correctFormat(customer)
{
  var first = customer.charAt(0).toUpperCase();
  var rest = name.substring(1).toLowerCase();
  return first + rest;
}
</script>
</head>

<body>

<!--nff Add a form for the user to enter information into.-->

  <form name="PizzaForm">

<!--nff add a title at the top of the Web Page-->

  <h1>The JavaScript Pizza Parlor</h1>

<!--nff add directions to the user for the information to be entered-->

  <p>
  <h4>Step 1: Enter your name, address, and phone number:</h4>

<!--nff change the font-->

  <font face="Courier New">

<!--nff insert a text field for user to enter their name, add spaces between the title of the text box and the box itself, specify the size of the input box, and the type of input into the box as text.-->
    Name: &nbsp;&nbsp;&nbsp;<input name="customer" size="50"
    type="text"><br>

<!--nff insert a text field for user to enter their address, specify the size of the input box, and the type of input into the box as text.-->
    Address: <input name="address" size="50" type="text"><br>

<!--nff Insert a text field for user to enter their city, add spaces between the title of the text box and the box itself, specify the size of the input box, and the type of input into the box as text.-->
    City: &nbsp;&nbsp;&nbsp;<input name="city" size="15" type="text">

<!--nff Insert text fields for the user to enter their state and zip, specify the sizes of the input boxes, and specify that the text to be entered into the boxes will be in all caps for the state box. These input boxes should be on the same line as the last one.-->
    State:<select name="state">
          <option selected value="PA">PA</option>
          <option value="NJ">NJ</option>
          <option value="NY">NY</option>
          <option value="DE">DE</option>
      </select>

    Zip: <input name="zip" size="5" type="text"><br>

<!--nff Insert a text field for the user to enter their phone number, insert spaces after the title of the box, specify the size of the box, and the type of input as text.-->
    Phone: &nbsp;&nbsp;<input name="phone" size="50" type="text"><br>

<!--nff Insert a text field for the user to enter their email address, insert spaces after the title of the box, specify the size of the box, and the type of input as text.-->
    Email: &nbsp;&nbsp;<input name="email" size="50" type="text"><br>
  </font>
 </p>

 <!--nff add second step to order a pizza-->
 <p>
   <h4>Step 2: Select the size of pizza you want:</h4>
   <font face="Courier New">

<!--nff Add radio buttons to choose from four options for pizza sizes.-->
     <input name="sizes" type="radio" value="small">Small
     <input name="sizes" type="radio" value="medium">Medium
     <input name="sizes" type="radio" value="large">Large
     <input name="sizes" type="radio" value="jumbo">Jumbo<br>
   </font>
 </p>
 <p>

  <!--nff add third step to order a pizza-->

   <h4>Step 3: Select the pizza toppings you want:</h4>
   <font face="Courier New">

<!--nff Add check boxes for user to choose toppings.-->
     <input name="toppings" type="checkbox" value="pepperoni">Pepperoni
     <input name="toppings" type="checkbox" value="canadian bacon">Canadian Bacon
     <input name="toppings" type="checkbox" value="sausage">Sausage<br>
     <input name="toppings" type="checkbox" value="mushrooms">Mushrooms
     <input name="toppings" type="checkbox" value="pineapple">Pineapple
     <input name="toppings" type="checkbox" value="black olives">Black Olives<br>
     <input name="toppings" type="checkbox" value="green peppers">Green Peppers
     <input name="toppings" type="checkbox" value="extra cheese">Extra Cheese
     <input name="toppings" type="checkbox" value="none">None<br>
    </font>
   </p>

 <!--nff Add buttons for the options to submit order or clear entries. Add an onClick event to show one of the alerts entered earlier in this document when the submit button is clicked at the bottom of the Web Page. Add and onClick event to clear the entries in this form upon clicking the clear entries button.-->
   <input type="button" value="Submit Order" onClick="doSubmit()">
   <input type="button" value="Clear Entries" onClick="doClear()">
  </form>
</body>

</html>

1
没能读完整个代码,但是为什么你用 "customer" 作为第一个字母,而在其余的子字符串中使用 "name"? - ggbranch
我犯了一个错误。在尝试了许多其他方法后,我重新输入了最后一次大写字母的尝试。在纠正了这个问题之后,如上所示,作为“customer”,它仍然对我不起作用。我想知道我是否将代码部分放在整个文档的错误位置。你认为呢? - Nina Fonseca
我尝试使用Ctrl + F查找您的代码,但找不到您调用函数的位置。您的函数是有效的。https://jsfiddle.net/903apjwm/ - ggbranch
我完全是新手,所以如果这个问题的答案很明显,请原谅我...你说的“你在哪里调用了函数”是什么意思? - Nina Fonseca
5个回答

2

您的函数只将字符串的第一个字母大写,而不是每个单词的第一个字母大写。您可以尝试使用 string.split(' ') 将字符串拆分为单独的单词:

function correctFormat(customer)
{
    if (customer == null || customer.length == 0)
        return customer;
    var words = customer.split(/\s+/g);
    for (var i = 0; i < words.length; ++i) {
        var first = words[i].charAt(0).toUpperCase();
        var rest = words[i].substring(1).toLowerCase();
        words[i] = first + rest;
    }
    return words.join(' ');
}

我还注意到你没有在任何地方调用correctFormat函数。你需要调用该函数才能执行它。例如:

var customer = correctFormat(document.PizzaForm.customer.value);

我应该在哪里调用correctFormat?是直接放在函数下面吗? - Nina Fonseca
1
@NinaFonseca 在需要使用它的地方调用该函数。你可能想要阅读有关函数的内容,因为你的理解似乎有限。我在我的答案中给出了如何调用它的示例 - 当你从文本框中读取customer的值时。 - AJ Richardson
我明白了!我不得不回头看在哪里调用函数。我已经在这上面工作了几天。我是新手,所以这对我来说非常困难。非常感谢您! - Nina Fonseca
2
@NinaFonseca 如果单词之间没有用空格分隔,这个函数将无法正常工作(例如,如果用户输入逗号或点号,比如“dr.bobby s.smith”)。请查看我的答案,以更好地处理此类输入:https://dev59.com/P4vda4cB1Zd3GeqPbZnH#30634187 - pisamce

2

您可以使用正则表达式,例如:

function correctFormat(customer){
    return customer.replace(/\b(.)(.*?)\b/g, function(){
        return arguments[1].toUpperCase() + arguments[2].toLowerCase();
    });
}

啊,是的。我明白你在说什么。这很有帮助。谢谢。 - Nina Fonseca

1
正如@Wee You所提到的,您在第一个字母中使用了customer,但在其余字母中使用了name。您需要使用用户输入调用此函数,然后使用正确的格式更新dom中的文本。
function correctFormat(str)
{
  var first = str.charAt(0).toUpperCase();
  var rest = str.substring(1).toLowerCase();
  return first + rest;
}

是的。我已经纠正了,但不幸的是,这仍然没有解决我的问题。我也尝试了你上面建议的代码,但它仍然没有以正确的格式打印输出。我已经尝试了很多组合,包括 CSS。 - Nina Fonseca
1
你需要获取用户输入的字符串并调用 correctFormat(input),最后将正确的输入写入到 DOM 中。 - tning

1
这里有一个小的示例代码,你需要将每个名称部分传递给.replace()方法:

var PizzaForm = document.PizzaForm;
var customer = PizzaForm.customer;

function formatName() {
  this.value = this.value.replace(/([^ \t]+)/g, function(_, str) {
    var A  = str.charAt(0).toUpperCase();
    var bc = str.substring(1).toLowerCase();
    return A + bc;
  });
}

customer.addEventListener("input", formatName);
<form name="PizzaForm">
  Name:  <input name="customer" size="50" type="text">
</form>

上述代码也适用于Paste。祝你玩得愉快。

PS:不要使用那个冗长的doClear(){代码块,为什么不直接使用PizzaForm.reset();来重置你的表单呢?


0

试试这个函数

function correctFormat(customer)
{
  var upperText = customer.toLowerCase();
  var result = upperText.charAt(0).toUpperCase();
  for(var i=1;i<upperText.length;i++)
     if(upperText.charAt(i-1) == ' ') 
        result += upperText.charAt(i).toUpperCase();
     else
        result += upperText.charAt(i);
  return result;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接