在Javascript IF语句中使用空格/连字符
Using spaces/hyphens in 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 {
document.write('');
}
</script>
上面的代码是这样设计的:每当单词是hello there
时,就会显示某个东西。然而,当单词之间有一个空格时,它不起作用:hello there
。我尝试使用连字符:hello-there
,但这也不起作用。
为了更好地阅读,它只在我写一个词时起作用:hellothere
或HelloThere
。
为什么会这样?有什么方法可以绕过它吗?
假设(因为您不会显示它){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()
。
相关文章:
- Javascript正则表达式,返回连字符和空格后面的数字
- 在 3 位和 6 位数字后插入空格或连字符,前缀为 +91
- 允许数字、空格、加号、连字符和括号的正则表达式
- 用连字符替换字符串中的空格
- 在 javascript 中查找非单词、非空格和非连字符
- 将空格和空格替换为逗号,并在 JS 中使用连字符
- java-script 中的正则表达式,仅接受 0-9 连字符和字母表中的数字,没有空格
- 正在尝试检索所有以空格、连字符、撇号或字符串开头的大写前导字符
- Javascript/jQuery:拆分camelcase字符串并添加连字符而不是空格
- Javascript字符串删除空格和连字符
- Regex捕获空格和特殊字符,除了单词中的连字符
- 逗号和空格分隔的数字和连字符分隔的字符串正则表达式
- 在Javascript IF语句中使用空格/连字符
- Regex允许单词字符、括号、空格和连字符
- 如何在正则表达式中只允许一个连字符(-)、一个空格()和一个撇号(')
- Regex for Should由8到20个数字字符组成,包括空格和一个连字符,并且连字符不能是第一个或最后一个字符
- 从字符串中删除空格、连字符和括号
- Javascript验证允许在名称中使用空格、连字符和外字符
- JavaScript 正则表达式由连字符和空格拆分
- 使用实时验证脚本 - 除 _(下划线)以外的特殊字符 - (连字符).(点)和空格