在Javascript IF语句中使用空格/连字符

Using spaces/hyphens in Javascript IF statement

本文关键字:空格 连字符 Javascript IF 语句      更新时间:2023-09-26

我正试图找到一种在javascript语句中使用空格和连字符的方法。

<script type='text/javascript'>
<!--
var {word} = '{word}';
if(
    {word} == 'hellothere' ||
    {word} == 'hello there' ||
    {word} == 'hello-there'
){ 
    document.write('blah blah'); 
}
else {  
    document.write('');
}
</script>

上面的代码是这样设计的:每当单词是hello there时,就会显示某个东西。然而,当单词之间有一个空格时,它不起作用:hello there。我尝试使用连字符:hello-there,但这也不起作用。

为了更好地阅读,它只在我写一个词时起作用:hellothereHelloThere

为什么会这样?有什么方法可以绕过它吗?

假设(因为您不会显示它){word}被扩展为hello there,您的代码变成:

var hello there = 'hello there';
if(
  hello there == 'hellothere' ||
  hello there == 'hello there' ||
  hello there == 'hello-there'
){ 
  document.write('blah blah'); 
}
else {  
  document.write('');
}

正如一些评论者所指出的,变量名中不能有空格。

为什么要用变量的内容来命名?这个版本可以正常工作:

var myword = '{word}';
if(
    myword == 'hellothere' ||
    myword == 'hello there' ||
    myword == 'hello-there'
){ 

你可以重写你的if来考虑空格和破折号:

if (myword.match(/^hello[ '-]*there$/i)) {

我想你在找

if ({word}.replace(/-| /g, "") == 'hellothere') { … }

(尽管存在明显的语法问题)。它只是在比较之前从{word}中删除所有连字符和空格。如果您想使其不区分大小写,请添加.toLowerCase()