Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  198] [ 5]  / answers: 1 / hits: 13384  / 9 Years ago, mon, march 23, 2015, 12:00:00

Lets say I have a string, but the text could be anything!




This is a test case




The 'boundary' is the count after a space, this means the charIndex =



(0) This
(5) is
(8) a
(10) test
(15) case



The above means from (0) to (5) the word equals 'this '.



If I wanted to know the word just used, I would need to substr start at charIndex and look backwards until indexOf(' ')



Example: If I wanted to find the word just used at charIndex (10) how would I instruct javascript to look backwards until the next space and give me the word a .



Is it possible to do this, with as little process time, using Javascript, or JQuery?



UPDATE



Instead of looking after the word and going back, I decided to achieve what I needed, I split the words and used each charIndex as a count. Code follows:



var u = new SpeechSynthesisUtterance();
var words = element.innerHTML.split(' ');
var a = 0;
u.text = element.innerHTML;
u.lang = 'en-UK';
u.rate = 0.7;
u.onboundary = function(event) {
console.log(words);
element.innerHTML = element.innerHTML.replace(words[a], '<strong>' + words[a] + '</strong>');
a++;
}


But as this is not the questions answer, still the best answer to reverse search a string is that which is marked correct, although it still needs some work depending on the string structure.


More From » jquery

 Answers
3

Not clear about exact question but you can use a combination of lastindexof, indexof and substr in your case or write your own stuff.



Note: No error handling etc. is being done. Please do that.



var stringToBeParsed=This is a test case
i = stringToBeParsed.lastIndexOf( ,8);
j = stringToBeParsed.indexOf( ,i+1);

document.getElementById('output').innerText = stringToBeParsed.substr(i,j-i);


Custom



function parseBackward(stringToBeParsed, indexOfSpace){
var output = '';
for (var i = indexOfSpace-1; i >= 0; i--) {
if(stringToBeParsed.charAt(i) == ' '){
break;
}
output = stringToBeParsed.charAt(i) + output;
}
document.getElementById('output').innerText = output;
}

[#38400] Sunday, March 22, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jocelynkarsynr

Total Points: 472
Total Questions: 98
Total Answers: 96

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
jocelynkarsynr questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Sat, Jul 11, 20, 00:00, 4 Years ago
Sun, May 10, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
;