javascript - 在字符串中的每个字符串实例之后插入一个空格

标签 javascript string split type-conversion numbers

我试图用空格分隔字符串中的单词。

例如,我想将 "twothousandninehundredfiftyeight" 转换为 "2958"(这样我可以稍后将其转换为 2958,但我我已经想通了)

我已经设法使用数组字典让它工作:

var dictionary = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty","thirty","fourty","forty","fifty","sixty","seventy","eighty","ninety","hundred","thousand"];

连同这两个功能:

function spaceinsert(x) {
  for (i = 0; i < dictionary.length; i++) {
    if (x.includes(dictionary[i])) {
      var pos = getIndicesOf(dictionary[i], x);
      for (g = 0; g < pos.length; g++) {
            if (pos[g] != -1 && pos[g] !=0) {
                x = [x.slice(0, pos[g]), " ", x.slice(pos[g])].join('');    
            }
      }
    }
  }
  return x
}

function getIndicesOf(searchStr, str, caseSensitive) {
    var searchStrLen = searchStr.length;
    if (searchStrLen == 0) {
        return [];
    }
    var startIndex = 0, index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    }
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + searchStrLen;
    }
    return indices;
}

(对不起,乱七八糟的代码,我是新手)

这适用于大多数数字。例如:

onethousandthreehundredsixtyfive转换为 1365,但无法处理其他数字,例如 seventhousandtwohundredtwentytwo 它转换为 7200twent ytwosixthousandfourhundredeightyeight 转换为 sixthousandfourhundredeighteight 我认为这与重复自身的“单词”有关(TWOhundredtwentyTWO ) 但我想不出解决这个问题的方法。

有什么想法吗?

最佳答案

按长度对字典进行排序,因此首先处理最长的单词,以防止“十四”拆分为“四十”,例如。

通过 | 连接字典单词创建一个 RegExp,并用括号括起来。使用标志 gi(全局,不区分大小写)。参见 regex101有关 RegExp 的更多信息。

现在将 String.replace() 与 patten 一起使用,并用匹配 + 空格替换每个匹配。 trim 结果以删除字符串后的空格。

const str = "twothousandninehundredfiftyeight"

var dictionary = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty","thirty","fourty","forty","fifty","sixty","seventy","eighty","ninety","hundred","thousand"].sort((a, b) => b.length - a.length)

const pattern = new RegExp(dictionary.join('|'), 'gi')

const result = str.replace(pattern, '$& ').trim()

console.log(result)

关于javascript - 在字符串中的每个字符串实例之后插入一个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58756405/

相关文章:

python - 在 Python 中分解这个字符串的最佳方法是什么?

r - 如何只保留 R 中复杂字符串中的信息?

javascript - observableArray 中可观察值的 knockout 计算

带a标签的javascript变量(字符串构建)

正则表达式填字游戏求解器

python - 如何传递文件名的路径

javascript - .getAttribute 不是函数

Javascript - 在数组中插入占位符值以保持数组长度

c# - 来自字符串帮助的日期。我可以转换成我想要的字符串,但我无法转换回来

java - 如何从分隔字符串中获取值?