i am trying to concat a query value into a link
wwww.test/video (query value) ".flv"
altought i think i did something wrong.
function doSomething() {
var test = new StringBuilderEx();
var a = querySt("number");
test.append("<h1>test</h1> ");
test.append("<a ");
test.append("href=\"http://test.com/video\"" + a + ".flv\" ");
test.append("Style =\"display:block;width:425px;height:300px;\" ");
test.append("id=\"player\" ");
test.append("</a> ");
test.append("<script language=\"JavaScript\" ");
test.append("> ");
test.append("flowplayer(\"player\" ");
test.append(", \"flowplayer-3.2.2.swf\" ");
test.append("); <\/script>");
return test.toString()
}
at the end all i get is a link with test.com/video and the the passed value. The StringBuilderEx is a JS script and queryST is
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
So it would be awesome if i get to know what am i not getting
where 1 is the query number.
href="http://test.com/video1.flv"
test.append("href=\"http://test.com/video\"" + a + ".flv\" ");
You have an extraneous \" there.
test.append("href=\"http://test.com/video" + a + ".flv\" ");
Also a missing >
test.append("id=\"player\" ");
should be
test.append("id=\"player\">");
Also, your link has no content to click on
test.append("</a> ");
should be
test.append("Click me!</a> ");
Related
I'm new to JavaScript and am trying to work through some errors. I've researched sites and made a few changes but still having trouble. Any assistance is appreciated.
The goal is to take selected items on a SharePoint list and click a button that will open an email with list data.
The errors are below:
SCRIPT1002: SCRIPT1002:
HTML1423: Malformed start tag. Attributes should be separated by whitespace.
HTML1409: Invalid attribute name character. Attribute names should not contain ("),('),(<), or (=).
HTML1422: Malformed start tag. A self closing slash should be followed by a U+003E GREATER-THAN SIGN (>).
HTML1423: Malformed start tag. Attributes should be separated by whitespace. Email.aspx (807,105)
HTML1409: Invalid attribute name character. Attribute names should not contain ("),('),(<), or (=).
Here's the latest code...
<script type="text/javascript"> </script>
<script src=".../jquery-1.12.4.js"</script>
<script src=".../jquery.min"</script>
<script src=".../sprestlib.bundle.js"</script>
<script src=".../vue.min.js"</script>
<script src=".../jquery-3.5.1.js"</script>
function clickMethod() {
var ctx = SP.ClientContext.get_current();
var items = SP.ListOperation.Selection.getSelectedItems(ctx);
sprLib.list('DRLs').items({
listCols: {
iD: {dataName:'ID'},
drlId: {dataName:'Title'},
artifactIdCopy: {dataName:'ArtifactID'},
assessmentId: {dataName:'AssessmentIDCopy'},
dueDate: {dataName:'TaskDueDate'},
AOREmails: {dataName:'AOREmails'},
startDate: {dataName:'Assessment_x0020_ID_x0020_LU_x00'},
teamMemberEmails: {dataName:'TeamMemberEmails'},
artifactLink: {dataName: 'Artifact_x0020_Link'},
drlItemLink: {dataFunc:function(objItem){return 'View DRL'}}
},
queryOrderby: 'Title';
})
.then(findSelectedItems(arrData, items);
.catch(function(errMsg){console.error(errMsg) });
}
function findSelectedItems(spData, selectedItems){
var emailBody = '';
for(var i = 0; i < selectedItems.length; i++){
var itemID = selectedItems[i].id;
for(var j = 0; j < spData.length; j++){
if (spData[i].iD == itemID){
emailBody += "Title: " + spData[i].drlId + "\r\n";
}
}
}
sendMail(emailBody);
}
function sendMail(bodyString) {
var message = encodeURIComponent(bodyString);
//var yourMessage = document.getElementById('AORNames');
var subject = document.getElementById('DRLID').value;
var emails = document.getElementById('AOREMails').value;
var mail = "mailto:" + emails + "?subject=" + subject + "&body=" + message;
window.location.href = mail;
}
</script>
<button #click="clickMethod()">Send Email</button>
I recommend splitting out the javascript into separate files. Then you'd just need to do <script src='/my-new-file.js'></script> in the html file instead of mixing and trying to match like what's happening at the moment.
Alternatively if you want to keep it like you have it now, on the first line, removing the closing script tag and move all of the other script tags outside. Like this:
<body><button #click="clickMethod()">Send Email</button>
<script src=".../jquery-1.12.4.js"</script>
<script src=".../jquery.min"</script>
<script src=".../sprestlib.bundle.js"</script>
<script src=".../vue.min.js"</script>
<script src=".../jquery-3.5.1.js"</script>
<script type="text/javascript">
function clickMethod() {
var ctx = SP.ClientContext.get_current();
var items = SP.ListOperation.Selection.getSelectedItems(ctx);
sprLib.list('DRLs').items({
listCols: {
iD: {dataName:'ID'},
drlId: {dataName:'Title'},
artifactIdCopy: {dataName:'ArtifactID'},
assessmentId: {dataName:'AssessmentIDCopy'},
dueDate: {dataName:'TaskDueDate'},
AOREmails: {dataName:'AOREmails'},
startDate: {dataName:'Assessment_x0020_ID_x0020_LU_x00'},
teamMemberEmails: {dataName:'TeamMemberEmails'},
artifactLink: {dataName: 'Artifact_x0020_Link'},
drlItemLink: {dataFunc:function(objItem){return 'View DRL'}}
},
queryOrderby: 'Title';
})
.then(findSelectedItems(arrData, items);
.catch(function(errMsg){console.error(errMsg) });
}
function findSelectedItems(spData, selectedItems){
var emailBody = '';
for(var i = 0; i < selectedItems.length; i++){
var itemID = selectedItems[i].id;
for(var j = 0; j < spData.length; j++){
if (spData[i].iD == itemID){
emailBody += "Title: " + spData[i].drlId + "\r\n";
}
}
}
sendMail(emailBody);
}
function sendMail(bodyString) {
var message = encodeURIComponent(bodyString);
//var yourMessage = document.getElementById('AORNames');
var subject = document.getElementById('DRLID').value;
var emails = document.getElementById('AOREMails').value;
var mail = "mailto:" + emails + "?subject=" + subject + "&body=" + message;
window.location.href = mail;
}
</script>
</body>
Just before your function clickMethod you are missing a starting <script> tag. That's why it says malformed start tag. It's missing. Hope that helps.
I have the following element below in my DOM.
<div id="klarna-checkout-container" style="overflow-x: hidden;">
<script type="text/javascript">
/* <![CDATA[ */
(function(w,k,i,d,n,c,l){
w[k]=w[k]||function(){(w[k].q=w[k].q||[]).push(arguments)};
l=w[k].config={
container:w.document.getElementById(i),
ORDER_URL:'https://checkout-eu.playground.klarna.com/yaco/orders/1234-fa14-4a0f-bf2d-5678',
AUTH_HEADER:'KlarnaCheckout 76c9bumqmkt8oy7wcpnr6',
LOCALE:'sv-SE',
ORDER_STATUS:'checkout_incomplete',
MERCHANT_TAC_URI:'https://demo.krokedil.se/klarnacheckout/terms/',
MERCHANT_NAME:'K500956',
GUI_OPTIONS:[],
ALLOW_SEPARATE_SHIPPING_ADDRESS:true,
PURCHASE_COUNTRY:'swe',
PURCHASE_CURRENCY:'SEK',
TESTDRIVE:true,
CHECKOUT_DOMAIN:'https://checkout-eu.playground.klarna.com',
BOOTSTRAP_SRC:'https://a.klarnacdn.net/kcoc/6788-345/checkout.bootstrap.js',
CLIENT_EVENT_HOST:'https://evt.playground.klarna.com'
};
n=d.createElement('script');
c=d.getElementById(i);
n.async=!0;
n.src=l.BOOTSTRAP_SRC;
c.appendChild(n);
try{
((w.Image && (new w.Image))||(d.createElement && d.createElement('img'))||{}).src =
l.CLIENT_EVENT_HOST + '/v1/checkout/snippet/load' +
'?sid=' + l.ORDER_URL.split('/').slice(-1) +
'&order_status=' + w.encodeURIComponent(l.ORDER_STATUS) +
'×tamp=' + (new Date).getTime();
}catch(e){}
})(this,'_klarnaCheckout','klarna-checkout-container',document);
/* ]]> */
</script>
</div>
I want to get the value after the word called AUTH_HEADER:. So the value I am looking for is KlarnaCheckout 76c9bumqmkt8oy7wcpnr6
I tried using the code below but it needs improvement.
<script>
$(document).ready(function() {
var get_klarna_checkout_container = $('#klarna-checkout-container').text().trim();
var klarna_checkout_container_index = get_klarna_checkout_container.indexOf('AUTH_HEADER:');
var klarna_checkout_container_index_2 = get_klarna_checkout_container.substr(klarna_checkout_container_index, 289);
console.log(klarna_checkout_container_index_2);
});
</script>
The output of console.log above is:
AUTH_HEADER:'KlarnaCheckout 76c9bumqmkt8oy7wcpnr6',
LOCALE:'sv-SE',
ORDER_STATUS:'checkout_incomplete',
MERCHANT_TAC_URI:'https://demo.krokedil.se/klarnacheckout/terms/',
MERCHANT_NAME:'K500956',
GUI_OPTIONS:[],
ALLOW_SEPARATE_SHIPPING_ADDRESS:true,
PURCHASE_CO
I am aiming for KlarnaCheckout 76c9bumqmkt8oy7wcpnr6
The problem with my code above is that it prints a lot of string instead of just adding characters from what I added in substr method.
Any help is appreciated. Thanks.
I went the regex route. The line to look for is
var found = klarna_checkout_container_index_2.match(/AUTH_HEADER:'(.+)'/);
var get_klarna_checkout_container = $('#klarna-checkout-container').text().trim();
var klarna_checkout_container_index = get_klarna_checkout_container.indexOf('AUTH_HEADER:');
var klarna_checkout_container_index_2 = get_klarna_checkout_container.substr(klarna_checkout_container_index, 289);
var found = klarna_checkout_container_index_2.match(/AUTH_HEADER:'(.+)'/);
console.log(found[1]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="klarna-checkout-container" style="overflow-x: hidden;">
<script type="text/javascript">
/* <![CDATA[ */
(function(w,k,i,d,n,c,l){
w[k]=w[k]||function(){(w[k].q=w[k].q||[]).push(arguments)};
l=w[k].config={
container:w.document.getElementById(i),
ORDER_URL:'https://checkout-eu.playground.klarna.com/yaco/orders/1234-fa14-4a0f-bf2d-5678',
AUTH_HEADER:'KlarnaCheckout 76c9bumqmkt8oy7wcpnr6',
LOCALE:'sv-SE',
ORDER_STATUS:'checkout_incomplete',
MERCHANT_TAC_URI:'https://demo.krokedil.se/klarnacheckout/terms/',
MERCHANT_NAME:'K500956',
GUI_OPTIONS:[],
ALLOW_SEPARATE_SHIPPING_ADDRESS:true,
PURCHASE_COUNTRY:'swe',
PURCHASE_CURRENCY:'SEK',
TESTDRIVE:true,
CHECKOUT_DOMAIN:'https://checkout-eu.playground.klarna.com',
BOOTSTRAP_SRC:'https://a.klarnacdn.net/kcoc/6788-345/checkout.bootstrap.js',
CLIENT_EVENT_HOST:'https://evt.playground.klarna.com'
};
n=d.createElement('script');
c=d.getElementById(i);
n.async=!0;
n.src=l.BOOTSTRAP_SRC;
c.appendChild(n);
try{
((w.Image && (new w.Image))||(d.createElement && d.createElement('img'))||{}).src =
l.CLIENT_EVENT_HOST + '/v1/checkout/snippet/load' +
'?sid=' + l.ORDER_URL.split('/').slice(-1) +
'&order_status=' + w.encodeURIComponent(l.ORDER_STATUS) +
'×tamp=' + (new Date).getTime();
}catch(e){}
})(this,'_klarnaCheckout','klarna-checkout-container',document);
/* ]]> */
</script>
</div>
I think function substr is wrong.
string.substr(beginIndex, length);
If you want to get only 'KlarnaCheckout 76c9bumqmkt8oy7wcpnr6' Please use:
var klarna_checkout_container_index = get_klarna_checkout_container.indexOf('AUTH_HEADER:') + 12;
var klarna_checkout_container_index_2 = get_klarna_checkout_container.substr(klarna_checkout_container_index, 36);
//This is one way to do it. Hope it helps.
let div = document.querySelector("#klarna-checkout-container script").innerText,
str = div.split(","),
authHeader;
for(let index in str){
let temp = str[index].split(":");
if(temp[0].trim() === "AUTH_HEADER"){
authHeader = temp[1].trim();
}
}
If you split the text with the key + ":'", second item of splitted index will contain the value at index 0 and then you can split it again with "'" or "'," which first element of its result will contain the value you are looking for.
const getHeaderValue = function (text, toFind) {
return text.split(toFind + ":'")[1].split("'")[0];
};
$(document).ready(function() {
var container = $('#klarna-checkout-container').text().trim()
console.log(getHeaderValue(container, 'AUTH_HEADER'))
})
Based on what your code currently outputs, just do this:
if (typeof klarna_checkout_container_index_2 == "string") {
klarna_checkout_container_index_2 = JSON.parse(klarna_checkout_container_index_2);
}
console.log(klarna_checkout_container_index_2["AUTH_HEADER"]);
I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}
Currently I put a function call against each element like so:
<textarea id="comment" cols=70 rows=5 onblur="cleanWordClipboard(this)" />
Is there a more generic/central approach to adding:
onblur="cleanWordClipboard(this)"
to all TextArea elements, so
<textarea id="comment" cols=70 rows=5/>
stays as is. I am thinking something like CSS which has rules to apply behaviours to all elements of a certain type.
Thanks.
EDIT1
So far I am trying, at the bottom of my page, which is actually a master layout page that includes all dynamic pages (using ASP.NET MVC):
<script language="JavaScript">
// Thanks to Johnathan Hedley for this code.
var swapCodes = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230); // dec codes from char at
var swapStrings = new Array("--", "--", "'", "'", "\"", "\"", "*", "...");
function cleanWordClipboard(input) {
// debug for new codes
// for (i = 0; i < input.length; i++) alert("'" + input.charAt(i) + "': " + input.charCodeAt(i));
var output = input.value;
for (i = 0; i < swapCodes.length; i++) {
var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
output = output.replace(swapper, swapStrings[i]);
}
//return output;
input.value = output;
}
$('textarea').blur(cleanWordClipboard);
</script>
EDIT2
<textarea cols=10 rows=20 class="plaintextbox"></textarea>
<script language="JavaScript">
[].forEach.call(document.getElementsByClassName('plaintextbox'), function (element) {
element.addEventListener('blur', cleanWordClipboard);
// the element will be this in the cleanWordClipboard call
});
// Thanks to Johnathan Hedley for this code.
var swapCodes = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230); // dec codes from char at
var swapStrings = new Array("--", "--", "'", "'", "\"", "\"", "*", "...");
function cleanWordClipboard(input) {
// debug for new codes
// for (i = 0; i < input.length; i++) alert("'" + input.charAt(i) + "': " + input.charCodeAt(i));
var output = input.value;
for (i = 0; i < swapCodes.length; i++) {
var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
output = output.replace(swapper, swapStrings[i]);
}
//return output;
input.value = output;
}
</script>
Yes, you can do this in vanilla JavaScript:
[].forEach.call(document.getElementsByClassName('comment'), function(element){
element.addEventListener('blur', cleanWordClipboard);
// the element will be this in the cleanWordClipboard call
});
Note that I assume you use class=comment instead of id=comment, as only one element in a document can have a given id.
Use Jquery and it will work for all textarea elements.
$('textarea').blur(function(){
// code from cleanWordClipboard
});
Or simply
$('textarea').blur(cleanWordClipboard);
A simple way with jQuery would be $("textarea").blur(cleanWordClipboard).
hi I have a few problems:
What might I get the word around the word selected, if the word before and after the selected word given limits only 20 words that surround the selected word?
how to get the correct position if the word in a paragraph have the same word, for example I have a sentence like this: foo laa foo doo then I choose the word "foo" whose position is in between the words laa and doo?
how to get word from a different paragraph?
for example:
p1 : I like the red shirt
p2: my mother did not like the red shirt
the word I selected is "mother", and I have to take 10 words around the word "mother" that is "I like the red dress" and "I do not like the red shirt."
notes:
question No. 2 is able to use the nextSibling and previousSibling?
this is my code i try :
<html>
<head>
<script type="text/javascript">
function getElements(){
var x = document.getElementsByTagName("body");
x = x[0].innerHTML;
x = x.replace(/&(lt|gt);/g, function (strMatch, p1){
return (p1 == "lt")? "<" : ">";});
var str = x.replace(/<\/?[^>]+(>|$)/g, "");
var emailPattern = /[_a-zA-Z0-9\.]+#[\.a-zA-Z0-9]+\.[a-zA-Z]+/gi;
var urlPattern = /[a-z]+:\/\/[^\s]+/gi;
var numberOrSymbolPattern = /[0-9\.,!##\$%\^\&*\(\)`~_\-=\+|\\{}\[\]\s:;<>\?\/]+/gi;
//////alert(str);
var str = str.replace(emailPattern , " ");
var str = str.replace(urlPattern , " ");
var str = str.replace(numberOrSymbolPattern , " ");
//////alert(str);
var str = str.replace(/[\n\f\r\t]/g, " ");
var hilangtandabaca = str.replace(/[.!:;'",?]/g," ");
var kataptg = hilangtandabaca;
//alert(kataptg);
var kata = new Array();
kata[0] = " is ";
kata[1] = " the ";
kata[3] = " of ";
kata[4] = " a ";
kata[5] = " or ";
kata[6] = " for ";
kata[7] = " from ";
kata[8] = " in ";
kata[9] = " this ";
kata[10] = " and ";
kata[11] = " on ";
kata[12] = " with ";
kata[13] = " my ";
for(var i=0,regex; i<kata.length; i++){
var regex = new RegExp(kata[i],"gi");
kataptg = kataptg.replace(regex," ");
}
var select = getSelected()+ "";
alert(select);
var index = kataptg.indexOf(select);
//alert("indeks select text:" + index);
if (index >= 0) {
var strBefore = "";
var strAfter = "";
//var strOri ="";
//if (index = -1)
//strOri = kataptg.substr(index);
//alert(strOri);
if (index > 0)
strBefore = kataptg.substr(0, index);
//alert(strBefore);
if (index < kataptg.length - 1)
strAfter = kataptg.substr(index + select.length, kataptg.length - (index + select.length));
//alert(strAfter);
alert("Before: " + strBefore + "\nAfter: " + strAfter);
}
}
function getSelected() {
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
} else if (document.selection) {
userSelection = document.selection.createRange();
}
return userSelection;
}
</script>
</head>
<body>
<h2>About</h2>
<p> my email : a#a.a
<p> my url http://id.wikipedia.org/wiki/URL
<p> my telepon number = 081330782
<p>okey In agriculture, the harvest is the process of gathering mature crops from the fields. Reaping is the cutting of grain or pulse for harvest, typically using a scythe, sickle, or reaper.[1] The harvest marks the end of the growing season, or the growing cycle for a particular crop, and this is the focus of seasonal celebrations of on many religions. On smaller farms with minimal mechanization, harvesting is the most labor-intensive activity of the growing season great yeah. !:;'",?</p>
<p>
<input type="button" onclick="getElements()" value="ambil select text" />
</p>
</body>
</html>
This is a perfect example of JavaScript's innerHTML and split() methods. You can loop through the content of all of the p elements. Here's an example of searching in the first paragraph:
contentArray = document.getElementByTagName('p')[0].innerHTML.split(' ')
split(' ') splits the content of the element into an array, separating by the spaces. innerHTML is self explanatory.
Now, to find your words. indexOf() is your friend in this case:
foodex = contentArray.indexOf('foo');
alert('The first occurrence of the string \'foo\' in the text is at word number ' + foodex);
Finally, to get surrounding words, just play with the array (this won't work if the occurrence of the string is close to the start or end of the paragraph, namely less than 10 words away:
alert('I am the 10th word after \'foo\'' + contentArray[foodex + 10 - 1]);
Good luck (no guarantees this code works out of the box)!