var user_name = prompt ("Write your name in the box below","Write it here");
document.write("Hello " + user_name + ". Welcome to my page!");
这就是我现在的代码。我想拥有它,这样一旦你说出你的名字,它就会说:
你好维多利亚。欢迎来到我的网站!您的姓名包含 8 个字符。
var user_name = prompt ("Write your name in the box below","Write it here");
document.write("Hello " + user_name + ". Welcome to my page!");
这就是我现在的代码。我想拥有它,这样一旦你说出你的名字,它就会说:
你好维多利亚。欢迎来到我的网站!您的姓名包含 8 个字符。
如果用户输入“Jon Dow”user_name.length // output 7
这将是不正确的,因为它会计算中间的空格。要解决此问题,您可以使用正则表达式的帮助!
改为使用
user_name.replace(/\s/g,"").length;
所以生成的代码将是:
document.write("Hello " + user_name + ". Welcome to my page! Your name contains " + user_name.replace(/\s/g, "").length + " characters.");
利用:
user_name.length
所有字符串都有一个包含字符串长度的长度属性。在您的代码中,这看起来像:
document.write("Hello " + user_name + ". Welcome to my page! Your name contains " + user_name.length + " characters.");