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個字符。
用途:
user_name.length
所有字符串有一個length屬性,它包含字符串的長度。在你的代碼,這將是這樣的:
document.write("Hello " + user_name + ". Welcome to my page! Your name contains " + user_name.length + " characters.");
如果用戶輸入一個名字進入「喬恩陶氏」 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.");
非常普遍的問題。沒有進行任何研究。 –