如何根据字符串中的单词数组获取单词字符在字符串中的位置

时间:2019-03-24 20:45:22

标签: javascript search

有一个很长的文本,其中有很多类型的空白。为了从中得到单词的数组,我要做     var words = whole_text.split(/ \ s + /);

现在,我想获得单词之后的文本[124],包括所有原始空白。我该怎么做?我这样做的原因是在单击字符后在文本中获得字符位置。也会很高兴听到其他方法。

4 个答案:

答案 0 :(得分:1)

从所需的单词索引中,一种选择是使用一个正则表达式,该重复表达式重复\S+\s的重复次数,这将与您感兴趣的单词索引匹配。例如:< / p>

const str = 'foo     bar baz buzz foooo barrr bazzz   buzzzz';
const words = str.split(/\s+/);

console.log(words[2]);
// to get the text after the word at [2]:
const re = new RegExp(String.raw`(?:\S+\s+){3}`);
const textAfterWords2 = str.replace(re, '');
console.log('text after ' + words[2] + ' is:');
console.log(textAfterWords2);

console.log(words[5]);
// to get the text after the word at [5]:
const re2 = new RegExp(String.raw`(?:\S+\s+){6}`);
const textAfterWords5 = str.replace(re2, '');
console.log('text after ' + words[5] + ' is:');
console.log(textAfterWords5);

// to get just the index in the original string:
const indexOfBarrrEnd = str.match(re2)[0].length;
console.log(indexOfBarrrEnd , str.slice(indexOfBarrrEnd ));

答案 1 :(得分:0)

如果需要单词的位置,可以使用findIndex

let words = whole_text.trim().split(/\s+/);
let position = words.findIndex(word => word === chosenWord);

我用修剪来削减多余的空白。

然后您slice原始文本:

console.log(whole_text.slice(position));

答案 2 :(得分:0)

类似的方法也可以处理重复:

var text="hello  world hello           world lorem ipsum";
var words=text.split(/\s+/);
for(var i=0;i<words.length;i++)
  console.log(i,"*"+text.match(words.slice(0,i).join("\\s+")+"(.*)")[1]+"*");

就我个人而言,我不会强制执行正则表达式。

答案 3 :(得分:0)

好吧,假设拥有所有单词的父代的ID为parent。然后您可以做类似的事情

const parent = document.querySelector("#parent");
parent.addEventListener("click", handleClick, false);

const handleClick = (e) => {
    if (e.target !== e.currentTarget) {
        // target is the element that triggered the event currentTarget is the element that the event listener is attached to.
        const i = Array.prototype.indexOf.call(parent.childNodes, e.target);
        console.log(i);
    }
    e.stopPropagation();
}

这应该给您单击哪个单词。如果您现在想找出在该单词中单击了哪个字符,可以按照Determine the position index of a character within an HTML element when clicked

中的答案进行操作。