簡體   English   中英

如何根據字符串中的單詞數組獲取單詞字符在字符串中的位置

[英]How to get position of a word characters in a string based on an array of words in this string

有一個長文本,其中有很多類型的空白。 為了得到一個單詞數組,我做var words = whole_text.split(/ \\ s + /);

現在,我想獲得單詞之后的文本[124],包括所有原始空白。 我該怎么做? 我這樣做的原因是在單擊字符后在文本中獲得字符位置。 也會很高興聽到其他方法。

從所需的單詞索引中,一種選擇是使用正則表達式,該規則表達式重復執行\\S+\\s的重復次數,這將與您感興趣的單詞索引匹配。例如:

 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 )); 

如果您需要單詞的位置,則可以使用findIndex

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

我用修剪來削減多余的空白。

然后slice原始文本:

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

像這樣的作品,也可以處理重復:

 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]+"*"); 

就我個人而言,我不會在此任務上強制使用正則表達式。

好吧,假設擁有所有單詞的parent具有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();
}

這應該給您單擊哪個單詞。 如果現在想找出在該單詞中單擊了哪個字符,則可以按照單擊時確定HTML元素內字符的位置索引中的答案進行操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM