Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript IF语句中使用空格/连字符_Javascript_If Statement - Fatal编程技术网

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

在Javascript IF语句中使用空格/连字符,javascript,if-statement,Javascript,If Statement,我试图找到一种在javascript语句中使用空格和连字符的方法 <script type='text/javascript'> <!-- var {word} = '{word}'; if( {word} == 'hellothere' || {word} == 'hello there' || {word} == 'hello-there' ){ document.write('blah blah'); } else { d

我试图找到一种在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>


我想你在找我

if ({word}.replace(/-| /g, "") == 'hellothere') { … }
(尽管存在明显的语法问题)。它只是在比较之前删除
{word}
中的所有连字符和空格。如果要使其不区分大小写,请添加
.toLowerCase()

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

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)) {

{word}
?请发布实际语法正确的代码。您的代码没有任何意义。除了废话,什么是
{word}
?当你发布这个问题时,它是废话。只有你提供了一些背景,情况就不那么糟了。但仅仅是。考虑到你只有一个<代码> JavaScript < /Cult>标签,在帖子中没有提到任何服务器。让我把它拼出来:你张贴了一些包含“代码> {Word } /代码>”的JavaScript代码。code>{word}
在JavaScript中是一个无意义的构造。直到你作了更多的评论,这个问题才开始有意义。哦,而且@FelixKling比我聪明。@Quintero在这一点上,这里评论的每个人都看到了问题,除了(显然)你。Andy理解你说的脚本的作用,但是考虑到原始代码和问题中的问题,他不愿意相信你的话。请考虑一下所提供的解释(下面是我的答案中的一个解决方案)。这个问题变成了一个讨厌的笑话。不是我。我试试这个。变量名中没有空格<代码>{word}不会更改。它是一个在我的服务器上工作的更大上下文中使用的变量。不,根据您上面的评论,当它在浏览器中实际运行时,它已被替换为
hello here
。如果这不是真的,那么(a)
{word}
不是有效的变量名,(b)
{word}
将永远不会匹配
“hello here”
或列表中的任何其他内容。