I would love some advice. I'm trying to get some text out of a long string. The string is here: http://espn.go.com/nba/bottomline/scores
I have the script that makes an HTTP request to get all this text, but need help only taking certian things from this long string.
I would like to grab this text from the long string:
Cleveland%20114%20%20%20LA%20Clippers%2090%20(FINAL)
Indiana%20at%20Atlanta%20(6:00%20PM%20ET)
Utah%20at%20Sacramento%20(6:00%20PM%20ET)
Milwaukee%20at%20Brooklyn%20(8:00%20PM%20ET)
New%20York%20at%20LA%20Lakers%20(9:30%20PM%20ET)
I'm not sure the best way to go about it.. Should I try to grab the text between each nba_s_left1= and &. If so, how would I go about that?
It seems that the whole long string is one big query string. So you can parse it with this js function:
function parseQuery(qstr) {
var query = {};
var a = qstr.substr(1).split('&');
for (var i = 0; i < a.length; i++) {
var b = a[i].split('=');
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
}
return query;
}
query = parseQuery(longString);
And then you can just get the part, that interests you, by calling query["nba_s_left1"]
Related
I have a few comma-separated URLs as shown below.
https://drive.google.com/open?id=17kTY2b3XvERC4wqZnLt7sVwMe8ZoDZUD, https://drive.google.com/open?id=1En1tNNLEgz5JiIk2GJnjNb_bhk23YJb2, https://drive.google.com/open?id=2En1tNNLEgz5JiIk3GJnjNb_bhk23YJb2
I need to get just the IDs (Example: 17kTY2b3XvERC4wqZnLt7sVwMe8ZoDZUD) from it in an array.
I'm a rookie coder and would appreciate it if someone can help me with the code.
Use the URL parsing library built-in to the browser. Don't attempt to use regular expressions to pick apart the URL because you don't have to (and you might end up getting it wrong).
var u = new URL("https://drive.google.com/open?id=2En1tNNLEgz5JiIk3GJnjNb_bhk23YJb2");
console.log(u.searchParams.get('id'));
> "2En1tNNLEgz5JiIk3GJnjNb_bhk23YJb2"
You could use string.split("?id=") and get the second element from the array returned (element 0 for everything to the left, 1 for the right)
E.G:
<script>
var myArray = ["https://drive.google.com/open?id=17kTY2b3XvERC4wqZnLt7sVwMe8ZoDZUD",
"https://drive.google.com/open?id=1En1tNNLEgz5JiIk2GJnjNb_bhk23YJb2",
"https://drive.google.com/open?id=2En1tNNLEgz5JiIk3GJnjNb_bhk23YJb2"];
for(var i=0; i<myArray.length; i++)
{
var result = myArray[i].split("?id=")[1];
console.log(result);
}
</script>
I'm trying to find certain words in a Google Document, in order to format them via script. The problem is, it seems like findText() is only able to find the word, when it's in the first paragraph. If it's somewhere else, findText() will go nuts and give me (seemingly) random locations for the word. Here is how it's coded:
function findBoldMarks(){
var doc = DocumentApp.openById('docId');
var docText = doc.editAsText();
// search initial bold markup
var srcB0 = body.findText('bold0');
var idB0 = srcB0.getStartOffset();
// search final bold markup
var srcB1 = body.findText('bold1');
var idB1End = srcB1.getEndOffsetInclusive();
// set markup and text wrapped within bold markup as bold
docText.setBold(idB0, idB1End, true);
}
I feel like I must be ignoring something basic here, but after hours struggling with it, I'm not sure anymore. I appreciate any thoughts. Thanks!
To continue searching past the first occurrence, you'll need to wrap the search in loop and provide the second "from" argument in findText().
Here's the start of an example that only searches for 1 word...
function findBoldMarks(){
var body = DocumentApp.getActiveDocument().getBody();
var pattern = "bold0";
var searchResult = body.findText(pattern);
var style = {};
style[DocumentApp.Attribute.BOLD] = true;
while (searchResult !== null) {
var thisElement = searchResult.getElement();
var thisElementText = thisElement.asText();
thisElementText.setAttributes(searchResult.getStartOffset(), searchResult.getEndOffsetInclusive(),style);
// search for next match
searchResult = body.findText(pattern, searchResult);
}
}
...derived from some answers in this post.
Maybe some one can modify to include the text between the two search terms. It doesn't appear that findText() accepts a regular expression search pattern, so another approach may be needed to do that.
I'm actually working on a website in which I'll need to replace many words by something like for example: banana by ******.
I use a website with php and mysql, but I also use javascript.
I have in my database a table in which are banned words.
I'm receive this words in an array from my database. i'm looking for a function that will be able to replace this words in all tha page. i can not use function like ob start.
The best will be a function that check on body onload and replace words.
This is a rather difficult task to tackle because:
People will try to circumvent this system by replacing certain letter, such as "s" with "$", "a" with "#", or by misspelling words that can still be understood
How will you deal with words like "password" that contains an swear word?
I would recommend going with a service that already has this figured out:
http://www.webpurify.com/
Look at this SO post: How do you implement a good profanity filter?
I'm going to use CoffeeScript, you can compile to JavaScript here if you wish or just use this as pseudocode.
String::replaceAll = (a, b) ->
regExp = new RegExp(a, "ig")
#replace regExp, b
_stars = (string) ->
str = ""
for i in [0..string.length]
str = "#{str}*"
str
bannedWords = [ "bannedword", "anotherbannedword" ]
_formSubmitHandler = (data) ->
for bannedWord in bannedWords
data.userInput = data.userInput.replaceAll bannedWord, _stars(data.userInput)
If the page content is as well coming from the database, or being entered into the database. Why not filter it using php prior to it being inserted or when it is pulled using str_replace
// PREFERRED WAY
$filteredContent = str_replace($bannedlist, "**", $content2Filter);
Or if you are looking for a javascript version, then you would need to use either multiple str.replace or regex. Something like:
var search = "/word1|word2|word3/gi"; //This would be your array joined by a pipe delimiter
var ret=str.replace(search,'**');
I made a very simple censoring method for this. It will only track words you put into the array of bad words. I would suggest you use an advanced library for word censors.
censor.js
var censor = (function() {
function convertToAsterisk(word) {
var asteriskSentence = '';
for(var asterisks=0;asterisks<word.length;asterisks++) {
asteriskSentence+='*';
}
return asteriskSentence;
}
return function(sentence, bannedWords) {
sentence = sentence || undefined;
bannedWords = bannedWords || undefined;
if(sentence!==undefined && bannedWords!==undefined) {
for(var word=0;word<bannedWords.length;word++) {
sentence = sentence.replace(bannedWords[word], convertToAsterisk(bannedWords[word]));
}
}
return sentence;
};
})();
The method can be used like so:
var sentence = 'I like apples, grapes, and peaches. My buddy likes pears';
var bannedWords = [
'pears',
'peaches',
'grapes',
'apples'
];
sentence = censor(sentence, bannedWords);
This system does not protect bad words within other words, or tricky mispellings. Only the basics.
var str="badword";
var ret=str.replace("badword","*******");
And to detect length automatically (useful for function useage)
var str="badword";
var ret=str.replace("badword",function() {
var ret = ""
for(var loop = 0; loop < str.length; loop++) {
var ret = ret + "*"
}
return ret
});
Finally I find my own way to make this system it is an easy way and you don't need to change all the code for all your website just the page that needs to be censored.
As far as I'm concerned I uses thausands of pages but the things is that I have one main page that included others pages.
For poeple who may be interested. all you have to do is to put this code at the beginning of your page so after the just put this code <?php ob_start(); ?> at the end of the body, before just put this code `
<?php
//We get the content of the page
$content = ob_get_contents();
// and we replace all
$content = str_replace('naughty', '*****', $content);
/// / VERY important, we must finish the page or in any case include ob_end_clean () function before echo $ content as PHP code would be displayed also
ob_end_clean ();
echo $content;
?>
This is an easy way, but you can also do an array for all censored words.
Full disclosure, I wrote the plugin.
I've written a jQuery plugin that does what you're looking for. It is not completely water tight, and others can very easily circumvent the plugin by disabling javascript. If you'd like to try it out, here's a link.
http://profanityfilter.chaseflorell.com/
And here's some example code.
<div id="someDiv">swears are ass, but passwords are ok</div>
<script>
$('#someDiv').profanityFilter({
customSwears: ['ass']
});
</script>
I'm trying to write a Javascript function to get the query string of the browser and allow a new key/value to be passed to the function. If the key exists, I need to replace the value. Since I've spent the last 3.5 hours on this, I haven't yet gotten around to the replacing part.
So far, I'm using the answer here: How to get the query string by javascript? to get the query string. However, it doesn't appear to work... The URL I was testing with was: http://www.site.com/poo?drwho=tombaker&companion=k9
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
assoc[decode(key[0])] = decode(key[1]);
}
if(assoc["dr"] === undefined ) {
// not found. todo: replace
}
I'd really appricate any help! Is there any simpler way of doing this using JQuery?
Copy and pasted your code here: http://jsfiddle.net/6KcWh/5/, and added a call to JSON.stringify() to examine the contents of assoc. It turns out assoc is not undefined. But, of course assoc.dr is undefined, because there is no querystring argument of dr. There is a querystring argument of drwho. It looks like you were looking for the wrong querystring argument.
You appear to be misusing for...in.
Try converting your for loop to a standard for (i = 0 ; i < keyValues.length; i++) and check out some other answers about what for...in is used for in JavaScript.
In JS, I'm having trouble working out how to split a string coming from an AJAX call.
This is what I have so far:
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
feedUpdateResponse = xmlhttp.responseText;
/////...split script.../////
}
}
xmlhttp.open("GET","https://myDomain.com/myScript.aspx",true);
xmlhttp.send();
Where you have /////...split script...///// in my script above, I need to add a little function that splits the string returned from my AJAX call.
The string simply contains names of DIVs, like this:
feedUpdateResponse = "div1/div2/div3/div4"
I would like to first split the string by its slashes (/) and run a loop through the different values and do stuff to those elements on my page.
To give an idea of what I need to achieve, I have given this example which is a mix of ASP & JS - it's the only way I can possibly describe it (and show that I've had an attempt) :)
MyArray = Split(feedUpdateResponse,"/")
For Each X In MyArray
documentGetElementById('updateAvailable_'+x).style.visibility="visible";
Next
On my page I have an ASP script that produces jquery carousels, all contained by separate DIVs. The DIVs are named DIV1, DIV2 etc. Inside DIV1, for example, is a text element called updateAvailable_div1 which will alert the user "There are new photos available for this feed, please click the refresh button".
Could somebody please explain to me how I can change my example above to work in JS? Just need to split the string into an array and loop through the split values...
You can use .split() to split a string on a specified character with the results returned as an array. So then it's just a matter of looping through the array:
// given your existing variable
// feedUpdateResponse = "div1/div2/div3/div4" as set in the
// code in the question, add this:
var a = feedUpdateResponse.split("/"),
i;
for (i = 0; i < a.length; i++) {
document.getElementById("updateAvailable_" + a[i]).style.visibility
= "visible";
}
Get your array via string.split("/"). Iterate your array using your method of choice. I prefer Array.forEach():
feedUpdateResponse.split("/").forEach(function (item) {
document.getElementById(item).style.visibility = "visible";
});
See the compatibility notes for using .forEach() in older browsers.
As an alternative:
for(element of feedUpdateResponse.split("/")){
do_your_thing();
}
Using for..in will end up giving you the indices on the array (keys), while for..on will give you the elements of the array (values).
You can also do:
for ([index, element] of Object.entries(feedUpdateResponse.split("/"))) {
do_your_thing();
}
In the event that you need the index.
The disadvantage is it not being compatible with IE, but for personal projects or a quick automation script it usually does me plenty fine.
Try this code:
var a = feedUpdateResponse.split("/");
for (i in a) {
document.getElementById("updateAvailable_" + a[i]).style.visibility
= "visible";
}
var feedUpdateResponse = "div1/div2/div3/div4";
var feedUpdateSplit = feedUpdateResponse.split("/");
for (var x = 0; x < feedUpdateSplit.length; x++) {
document.getElementById("updateAvailable_" + feedUpdateSplit[x]).style.visibility = "visible";
}