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:}
, ie 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.
You should start from the index of "{Picker:}"
+ 9, because the length of the particular string is 9.
Parse till the the index of '\n'
which is the line break character.
String.prototype.substr()
is deprecated, use String.prototype.substring()
instead.
function getWord() { var val = $("#myBox").val(); var myString = val.substring((val.indexOf("{Picker:}")) + 9, val.indexOf('\n')); $("#ans").text(myString); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <textarea id="myBox"> {Picker:} Helper This is just demo... </textarea> <br /> <span id="ans"></span> <br /> <input type="button" onclick="getWord()" value="Click" />
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/
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.