我的代码是这样的:

var obj = { 'one ': '1 ', 'two ': '2 ', 'three ': '3 ', 'four ': '4 ', 'five ': '5 ', 'six ': '6 ', 'seven ': '7 ', 'eight ': '8 ', 'nine ': '9 ', 'zero ': '0 ',
  ' one': '1 ', ' two': '2 ', ' three': '3 ', ' four': '4 ', ' five': '5 ', ' six': '6 ', ' seven': '7 ', ' eight': '8 ', ' nine': '9 ', ' zero': '0 ',
};


var str = 'the store number is one two three four'
//Checking if the string has any numbers in words..
if(str.indexOf('one') > -1 || str.indexOf('two') > -1 || str.indexOf('three') > -1 || str.indexOf('four') > -1 || str.indexOf('five') > -1
|| str.indexOf('six') > -1 || str.indexOf('seven') > -1 || str.indexOf('eight') > -1 || str.indexOf('nine') > -1 || str.indexOf('zero') > -1) {
  str = str + ' ';
  //Looping each word in the array and replacing the number word in the string with the respective number
  for(var i in obj) {
    if (str.indexOf(i) !== -1){
     str = str.replace(i, obj[i])
      //console.log (i, obj[i])
     }

  }
console.log(str)
}


我的任务是首先检查字符串是否包含0到9之间的数字(例如“零”,“一个”,“两个” ...“九”)。如果找到任何一个,那么我必须将其替换为它们各自的整数值,如“ 0”,“ 1”。

输入:“商店是一二三四”
转换后应为:
输出:“商店是1 2 3 4”

上面的代码完成了工作。但是我可以用正则表达式得到压缩代码吗?

最佳答案

问题中的代码具有两个冗余的if条件,可以将其简化为:

var obj = { 'one ': '1 ', 'two ': '2 ', 'three ': '3 ', 'four ': '4 ', 'five ': '5 ', 'six ': '6 ', 'seven ': '7 ', 'eight ': '8 ', 'nine ': '9 ', 'zero ': '0 '};

var str = 'the store number is one two three four '; // if we don't add a space after the 'four' - it will not be replaced!
for(var i in obj) {
    while (str.indexOf(i) > -1) {
        str = str.replace(i, obj[i]);
    }
}
console.log(str); // the store number is 1 2 3 4


不,正则表达式不会使此代码更简洁!

08-06 03:06