我有一根绳子:

const str = 'a string, a long string'

我想把它分解成单词(这里没有问题),然后跟踪原始字符串中每个单词的索引.

实际结果:

[
  { word: 'a',      idx: 0 },
  { word: 'string', idx: 2 },
  { word: 'a',      idx: 0 },
  { word: 'long',   idx: 12 },
  { word: 'string', idx: 2 }
]

预期结果:

[
  { word: 'a',      idx: 0 },
  { word: 'string', idx: 2 },
  { word: 'a',      idx: 10 },
  { word: 'long',   idx: 12 },
  { word: 'string', idx: 17 }
]

到目前为止的代码:

const str = 'a string, a long string'

const segmenter = new Intl.Segmenter([], { granularity: 'word' })

const getWords = str => {
  const segments = segmenter.segment(str)
  return [...segments]
    .filter(s => s.isWordLike)
    .map(s => s.segment)
}

const words = getWords(str)

const result = words.map(word => ({
  word,
  idx: str.indexOf(word)
}))

console.log(result)

推荐答案

您正在迭代的对象,其中包含segment以及它是否为isWordLikealso have the 102:

const str = 'a string, a long string'

const segmenter = new Intl.Segmenter([], { granularity: 'word' })

const getWordsWithIndexes = str => {
  const segments = segmenter.segment(str)
  return [...segments]
    .filter(s => s.isWordLike)
    .map(s => ({ idx: s.index, word: s.segment }))
}

const result = getWordsWithIndexes(str)

console.log(result)

以下是前type definition名:

interface SegmentData {
    /** A string containing the segment extracted from the original input string. */
    segment: string;
    /** The code unit index in the original input string at which the segment begins. */
    index: number;
    /** The complete input string that was segmented. */
    input: string;
    /**
     * A boolean value only if granularity is "word"; otherwise, undefined.
     * If granularity is "word", then isWordLike is true when the segment is word-like (i.e., consists of letters/numbers/ideographs/etc.); otherwise, false.
     */
    isWordLike?: boolean;
}

Javascript相关问答推荐

使用print This时, map 容器已在LeafletJS中初始化

我不知道为什么我的JavaScript没有验证我的表单

使用JavaScript单击上一个或下一个特定按钮创建卡滑动器以滑动单个卡

如何在JavaScript文件中使用Json文件

并不是所有的iframe都被更换

查询参数中的JAVASCRIPT/REACT中的括号

如何在我的Next.js项目中.blob()我的图像文件?

为什么可选参数的顺序会导致问题?

从逗号和破折号分隔的给定字符串中查找所有有效的星期几

在Odoo中如何以编程方式在POS中添加产品

用另一个带有类名的div包装元素

有没有办法通过使用不同数组中的值进行排序

AG-GRIDreact 显示布尔值而不是复选框

在高位图中显示每个y轴系列的多个值

TabNavigator和StackNavigator之间的Reaction Native中的导航问题

Played link-Initialize.js永远显示加载符号

如何按区域进行过滤并将其从结果数组中删除?

Reaction路由v6.4+数据API:重试加载程序而不显示错误

浮动标签效果移除时,所需的也被移除

检测带有委托的元素内部的点击,以及元素何时按其类名被选中