2012-09-25 101 views
-1
var user_name = prompt ("Write your name in the box below","Write it here"); 
document.write("Hello " + user_name + ". Welcome to my page!"); 

这是我现在的代码。我想拥有它,所以一旦你给你的名字,它会说,例如:如何计算字符串中的字符数?

你好维多利亚。欢迎来到我的网站!你的名字包含8个字符。

+0

非常普遍的问题。没有进行任何研究。 –

回答

1

用途:

user_name.length 

所有字符串有一个length属性,它包含字符串的长度。在你的代码,这将是这样的:

document.write("Hello " + user_name + ". Welcome to my page! Your name contains " + user_name.length + " characters."); 
2

如果用户输入一个名字进入“乔恩陶氏” 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.");