Search code examples
javascriptjquerystringsubstr

Find white space in a string back from an index position


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.


Solution

  • 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;
    }