'Find the word after specific word

i am new in javascript. I have below code where textarea contains text as...

<textarea id="myBox" >
{Picker:} Helper
This is just demo...
</textarea> 
<br/>
<span id="ans"></span> <br/>

<input type="button" onclick="getWord()" value="Click"/>  

i am trying to find out the word exact after the {Picker:}, i.e. i want to find word "Helper". So word {Picker:} is the point from where i am starting to find immediate word after it. For this i using indexOf. What i did uptil now is ...

<script> 
    function getWord() {

        var val = $("#myBox").val();
        var myString = val.substr((val.indexOf("{Picker:}")) + parseInt(10), parseInt(val.indexOf(' ')) );
        $("#ans").text(myString);
    }
</script>

will anyone guide me to find what mistake i am making. Thanks in advance.



Solution 1:[1]

var val = $("#myBox").val();
console.log(val)
var tempArray = val.replace("\n", " ").split(" ");
var wordToFind;

for(var i = 0 ; i < tempArray.length; i++) {
    var word = tempArray[i];
  
  if (word == "{Picker:}") {
        wordToFind = tempArray[i + 1]
  }
}

console.log(wordToFind)

This will assign what ever word comes after Picker: to the wordToFind variable. Check working :https://jsfiddle.net/o5qasnd0/14/

Solution 2:[2]

You could do something like this

const text = "{Picker:} Helper";

const wordArr = text.split(' ');
const idx = wordArr.indexOf('{Picker:}');
console.log(idx != -1 && (idx + 1) < wordArr.length ? wordArr[idx + 1] : 'not found');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Menno Spijker
Solution 2 AnanthDev