从 URL 变量获取值并显示它

getting value from URL variable and displaying it

我正在尝试显示一条问候消息,后跟从 URL 中获取的名称值。它可以工作,但是如果没有变量名,则即使是问候消息也不会显示任何内容。是什么导致了这个问题?

<h1 class="welcomeGreeting" style="color: white !important; text-align: center; padding-bottom:1px !important; margin-bottom:1px !important;">
</h1><script>
    var url = window.location.href;
    var captured = /name=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
    var result = captured ? captured : 'myDefaultValue';
//var result = window.location.href.split('&name=')[1];


  window.alert(result);
  var thehours = new Date().getHours();
 var themessage;
 var morning = ('Good morning');
 var afternoon = ('Good afternoon');
 var evening = ('Good evening');

 if (thehours >= 0 && thehours < 12) {
      themessage = afternoon + ' ' + result;

 } else if (thehours >= 12 && thehours < 17) {
      themessage = afternoon + ' ' + result;

 } else if (thehours >= 17 && thehours < 24) {
      themessage = afternoon + ' ' + result;
 }

 $('.welcomeGreeting').append(themessage);

</script>

It works, however if there is no variable name, nothing shows even the greeting message. What could be causing this issue?

如果找不到匹配项,

exec 将 return null。因此,当 url.

中不存在变量时,您正在尝试执行 null[1]

你需要先取一个变量中的值,然后从中提取值

var captured = /name=([^&]+)/.exec(url);
var result = captured ? captured[1] : 'myDefaultValue';