函数来大写字符串中每个单词的第一个字符

时间:2018-05-15 01:18:06

标签: javascript capitalize

这是尝试将“姓氏,名字”大写,但它不起作用。我无法弄清楚为什么它不起作用。你能帮我解决这个问题吗?

function validateForm() {

  var memName = document.getElementById('mem-name').value;
  var memRating = document.getElementById('mem-rating').value;
  var memClass = document.getElementById('mem-class').value;

  if (memName == "") {
    alert("Name must be filled out");
    return false;
  }
  if (memRating == "") {
    alert("Rating must be filled out");
    return false;
  }
  if (memClass == "") {
    alert("Class must be filled out");
    return false;
  }

  capitalize_Words(memName);

  //capitalize_Words 
  function capitalize_Words(memName) {
    return memName.replace(/\w\S*/g, function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
  }

  members.push({
    Name: memName,
    Class: memClass,
    Rating: memRating,
  });

  let temp = "New player added: " + memName;
  alert(temp);
  document.getElementById("newMember").reset();

}

1 个答案:

答案 0 :(得分:2)

字符串是不可变的;简单地调用capitalize_Words(memName);调用字符串上的replace不会改变字符串,只需返回新字符串。您的代码正在调用capitalize_Words并忽略结果;将结果存储在变量中。

function validateForm() {
  const memName = document.getElementById('mem-name').value;
  const memRating = document.getElementById('mem-rating').value;
  const memClass = document.getElementById('mem-class').value;
  if (memName == "") {
    alert("Name must be filled out");
    return false;
  }
  if (memRating == "") {
    alert("Rating must be filled out");
    return false;
  }
  if (memClass == "") {
    alert("Class must be filled out");
    return false;
  }
  const capitalizedMemName = capitalize_Words(memName);
  function capitalize_Words(memName) {
    return memName.replace(/\w\S*/g, function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
  }
  members.push({
    Name: capitalizedMemName,
    Class: memClass,
    Rating: memRating,
  });
  const temp = "New player added: " + memName;
  alert(temp);
  document.getElementById("newMember").reset();
}