Node Js代码替换0-9

时间:2017-11-28 03:38:40

标签: node.js

我的代码是这样的:

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','one','two'......'nine')。如果找到任何,那么我必须用它们各自的整数值替换为'0','1'..

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

以上代码完成了这项工作。但我可以使用正则表达式或其他东西获得压缩代码吗?

2 个答案:

答案 0 :(得分:0)

我在这里使用正则表达式并没有什么好处。这似乎要求使用静态的已知值进行简单的字符串替换。

也许是这样的

var str = 'the store number is one two three four'
var strArray = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

strArray.forEach(function(thisStr) {
    if (str.toLowerCase().includes(thisStr)) {
        console.log("String includes " + thisStr);
    }
});

str = str.replace('zero','0').replace('one','1').replace('two','2').replace('three','3').replace('four','4').replace('five','5').replace('six','6').replace('seven','7').replace('eight','8').replace('nine','9');
console.log(str);

答案 1 :(得分:0)

问题中的代码有两个冗余的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 

不,正则表达式使这段代码更简洁!