javascript - replace from A to B [closed] - javascript

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm trying to make a chrome extension to replace comments of known trolls in a forum by silence.
is there a way to tell .replace to replace text from a startpoint to an endpoint?
i.e.: replace text starting with 'Name' until 'end of post' by ""
thanks in advance
edit:
to meet the comments:
walk(document.body);
function walk(node)
{
var child, next;
switch ( node.nodeType )
{
case 1: // Element
case 9: // Document
case 11: // Document fragment
child = node.firstChild;
while ( child )
{
next = child.nextSibling;
walk(child);
child = next;
}
break;
case 3: // Text node
handleText(node);
break;
}
}
function handleText(textNode)
{
var v = textNode.nodeValue;
var regexReplace = "Name of troll(.*)"
v = v.replace(new RegExp(regexReplace), '');
textNode.nodeValue = v;
}
this is what the html looks like:
class="up" style="padding-left: 14px" id="pid_31519766" data-pid="31519766"><div class="posting08 ch_wissenschaft"><div class="thread" style="width: 505px" id="t31519766" data-pid="31519766"><div class="row1"><div class="l" style="width:336px "><a class="offset" name="pid31519766"></a><div class="uname" style="max-width:277px "><a rel="nofollow" href="/Userprofil/ByPosting/31519766">NAME OF TROLL</a></div><div class="utools"><a rel="nofollow" class="follow" onclick="STD.FollowingRelationships.followUser(31519766,1363710557719,escape('Orakel von Silesia'))" title="Mitposter von „NAME OF TROLL” werden. „NAME OF TROLL” hat 7 Mitposter.">7</a></div></div><div class="r"><a class="std-button rate p" title="Sehr lesenswert" rel="nofollow" onclick="STD.Forum.rate('31519766',1);">+</a></div><div class="r"><a class="std-button rate n" title="Nicht lesenswert" rel="nofollow" onclick="STD.Forum.rate('31519766', 0);">-</a></div><div class="r rating"><span class="l counter n">14</span><span class="l bar"><span class="wrapper"><span class="n"></span><span class="p"></span></span></span><span class="l counter p">1</span></div><div class="clear"></div></div><div class="row2"><div class="l date" data-timestamp="11.5.2013 15:08:13"><span class="absolute">11.5.2013, 15:08</span><span class="relative"></span></div><div class="r a"><a rel="nofollow" title="Klicken Sie hier, wenn Sie auf dieses Posting antworten möchten." class="onclick" onclick="STD.Forum.post({action: 'reply', id: '31519766', trigger: this}); return false;">antworten</a></div><div class="r p"><a rel="nofollow" title="Mit diesem Link können Sie die URL des Postings aufrufen." href="/plink/1363710557719/31519766">permalink</a></div><div class="r m"><a rel="nofollow" title="Melden Sie Postings an die Redaktion, wenn diese den Community Richtlinien widersprechen." onclick="STD.Forum.report('31519766');">melden</a></div><div class="clear"></div></div></div><div
class="txt" style="width: 505px">
POST I WANNA GET RID OF
</p></div></div></div><div

You could use replace with a regex:
General case (fiddle here):
function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }
var A = 'AAA'; // string A
var B = 'BBB'; // string B
var testStr = "BEFORE AAA WILL BE REMOVED BBB AFTER CCC BBB again DDD"; // string to be replaced
var stopAtFirstBMatch = testStr.replace(new RegExp(escapeRegExp(A)+'(.*?)'+escapeRegExp(B)), '');
console.assert(stopAtFirstBMatch == "BEFORE AFTER CCC BBB again DDD");
var stopAtLastBMatch = testStr.replace(new RegExp(escapeRegExp(A)+'(.*)'+escapeRegExp(B)), '');
console.assert(stopAtLastBMatch == "BEFORE again DDD");
Your case (fiddle here):
The regex Name(.*?)end of post will match anything starting from 'Name' to the first 'end of post' it finds. ((.*?) is a non-greedy match everything);
In case you mean end of post is the actual end of post, you can use Name(.*) as the regex. It will match every text starting with Name.
var strTest = "Hello my Name is this thal go away until the end of post problem goes away."
var regexEndOfPost = "Name(.*?)end of post"
// alerts: 'Hello my problem goes away'
alert(strTest.replace(new RegExp(regexEndOfPost), ''));
var regexNameToEnd = "Name(.*)" // in case you want from 'Name' to the end of the string
console.log(strTest.replace(new RegExp(regexNameToEnd), ''));
// alerts: 'Hello my '
alert(strTest.replace(new RegExp(regexNameToEnd), ''));

Related

array.find() always shows the same array

I'm currently learning JS/jQuery and thought I'd code a quiz for practice. While I managed to code the basics of the quiz I am struggling with a crucial part of my code.
In this quiz, I have an Array containing 10 objects. Each object has a question (String), options (Array), an answer (String) and a Boolean which indicates whether or not a question has been answered. Further, I filter this array to include only those elements, that haven't been asked/answered yet. However, this unansweredArr always contains 10 elements, even if I call the function again before asking the new question.
What I aim to do is the following:
Generate an array, that holds every question that hasn't been
answered yet. This is being done with
var unansweredArr = data.filter(function(question){
return question.answered === false;
});
Then I generate a random number, which will be used to grab an element out of this array. Said element then is being displayed in my HTML
When the player clicks on an option, the given answer will be checked. If correct, the player's score will be increased by 1 and the next question will be asked. Also answered: false will be set to answered: true on that specific question.
Until step 3, everything works like a charm (for me ;)) However, step 4 and further are my main problems.
Basically, step 2 and 3 should be repeated. Thus, the array should filter for every Object with answered: false. This array should update and contain 9 elements now - However, it doesn't. It still contains 10 elements and I don't know why. I tried to call the filter function again, without success. I tried refactoring some code by moving bits and pieces around, but nothing worked for me. Additionally, when checking for the right answer, it seems like the answer to the question that has been first answered is saved and will be used to for all the other questions.
Please find my code here:
var data = [{
question: "Cabrio: Check! Glas wird geext / Na klar gibt es Sex, weil ich parshippe jetzt!",
options: ["Gzuz", "Bonez MC", "RAF Camora", "LX"],
answer: "Gzuz",
answered: false
},
{
question: "Die Presse will mich mit Monsterbräuten in Bondfahrzeugen knipsen / Es ist wie Naturgewalten, weil Blitze vor dem Don erleuchten (Donner leuchten), Bitches!",
options: ["Kollegah", "Farid Bang", "Ali As", "Fatoni"],
answer: "Kollegah",
answered: false
},
{
question: "Frage: Was haben ein Rabbi, ein Priester, ein Koch mit 3 Eiern / ein Flyerverteiler mit einem Paket Flyern / ein Esel, zwei Geier, ich und 300 Freier gemeinsam? / Könnten alle dein Vadder sein!",
options: ["Snaga", "Pillath", "Torch", "KC Rebel"],
answer: "Snaga",
answered: false
},
{
question: "Denkt ihr, die Flüchtlinge sind in Partyboote gestiegen / mit dem großen Traum, im Park mit Drogen zu dealen?",
options: ["Tarek", "Maxim", "Nico", "DJ Craft"],
answer: "Tarek",
answered: false
},
{
question: "Rapper reden über Muskeln oder Brustumfang / Ich bin so ein Sklave, ich muss Benz fahren aus Gruppenzwang",
options: ["Shindy", "Bushido", "Fler", "Sido"],
answer: "Shindy",
answered: false
},
{
question: "Widerlich, Bitch! / Also glaub nicht, dass du Hund hier'n Aufreißer wirst (Hirn auf Reis servierst) wie'n China-Imbiss",
options: ["Kollegah", "Majo", "Jizi", "Gozpel"],
answer: "Kollegah",
answered: false
},
{
question: "Ich bin nicht nur der King dieser Mucke – ich bin diese Mucke!",
options: ["Kool Savas", "Eko Fresh", "Moe Mitchell", "Kaas"],
answer: "Kool Savas",
answered: false
},
{
question: "Ich brauch' Para, damit F*ckf*tzen blasen, ich muss Fixkosten tragen, die kann Rick Ross nicht zahlen.",
options: ["SSIO", "Schwester Ewa", "Xatar", "Abdi"],
answer: "SSIO",
answered: false
},
{
question: "Hater schauen und bauen sich einen Fake-Account, doch wissen, dass mein Album hitlastig ist/Hitlers Dick isst wie Eva Braun.",
options: ["Ali As", "Kollegah", "Farid Bang", "Majo"],
answer: "Ali As",
answered: false
},
{
question: "Dein Rap ist voller Tiefsinnigkeit/ Dass man als Zuhörer denkt, dein Schniedel ist klein",
options: ["SSIO", "Edgar Wasser", "Juse Ju", "Azad"],
answer: "SSIO",
answered: false
},
];
//Generate a score variable
var score = 0;
//Generate an array, which includes all the unanswered questions
var unansweredArr = data.filter(function(question) {
return question.answered === false;
});
//Random Number in order to get a random element from the array
var randomIndex = Math.floor(Math.random() * unansweredArr.length);
//Display random element/question in HTML
$("#question").text(unansweredArr[randomIndex].question);
for (var i = 0; i < 4; i++) {
$("#Option" + (i + 1)).text(unansweredArr[randomIndex].options[i]);
}
//What happens when the person answers the question
$(".Rapper").on("click", function() {
unansweredArr[randomIndex].answered = true;
var selected = $(this).text();
var trueAnswer = unansweredArr[randomIndex].answer;
//Check if answered correctly
if (auswahl === wahreAntwort) {
//Increase score by 1 and ask next question
console.log("Correct");
next();
return score = score + 1;
} else {
console.log("Wrong");
next();
return score;
}
});
function next() {
var unansweredArr = data.filter(function(question) {
return question.answered === false;
});
//Check if the array of unanswered questions is not empty
if (unansweredArr.length !== 0) {
//New random number
var randomIndex = Math.floor(Math.random() * unansweredArr.length);
//Display question and options in html
$("#question").text(unansweredArr[randomIndex].question);
for (var i = 0; i < 4; i++) {
$("#Option" + (i + 1)).text(unansweredArr[randomIndex].options[i]);
}
} else {
console.log("Game Over");
console.log(score);
}
}
/* Problems:
- unansweredArr does not update after a question has been answered.
- Answer to the first question will be the answer for the following questions.
*/
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
Zurück.
<div>
<!-- Frage Block -->
<div>
<p id="question">-- This is, where the punchline will be displayed --</p>
</div>
<!-- Antwort Möglichkeiten -->
<div>
<div>
Rapper 1
</div>
<div>
Rapper 2
</div>
<div>
Rapper 3
</div>
<div>
Rapper 4
</div>
</div>
</div>
The problem is that you define the same variables randomIndex and unansweredArr as global variables and as local variables in the function next.
When you update their value in the function next, the global variables with the same names do not change.
As a consequence you are always marking the first random question as answered:
unansweredArr[randomIndex].answered = true;
These are the global variables, and randomIndex does not reflect the most recently generated number.
Solution: remove the word var from before these variable names in the function next.
I did not check for other errors, but this one explains the behaviour you describe.

Parse string to get href given attribute value

I have a string with the following content:
var string =
'<div class="product-info-inner-content clearfix ">\
<a href="http://www.adidas.co.uk/ace-17_-purecontrol-firm-ground-boots/BB4314.html"\
class="link-BB4314 product-link clearfix "\
data-context="name:ACE 17+ Purecontrol Firm Ground Boots"\
data-track="BB4314"\
data-productname="ACE 17+ Purecontrol Firm Ground Boots" tabindex="-1">\
<span class="title">ACE 17+ Purecontrol Firm Ground Boots</span>\
<span class="subtitle">Men Football</span>\
</a>\
</div>';
I am trying to perform the JavaScript equivalent of the following Python code, in which uses beautiful soup to grab the URL of the div class element given a product code (i.e. in this case BB4314).
is_listing = len(soup.findAll(name="div", attrs={"class": "product-tile"})) > 1
if is_listing:
# stuck from this part
attrs = {"class": re.compile(r".*\bproduct-link\b.*"), "data-track": code}
url = soup.find(name="a", attrs=attrs)
url = url["href"]
How can I do this?
Just use DOM
var string = '<div class="product-info-inner-content clearfix "><span class="title">ACE 17+ Purecontrol Firm Ground Boots</span> <span class="subtitle">Men Football</span></div>',
div = document.createElement("div");
div.innerHTML = string;
var href = div.querySelector("a.product-link").href,
parts = href.split("/"),
code = parts.pop().split(".")[0];
console.log(code)
console.log(div.querySelector("a.product-link").getAttribute("data-track"))

How to get <img> src value from xml file?

I am trying to create a simple rss feed website.
I can get a few of rss feeds by just doing this:
let article = {
'title': item.title,
'image': item.image.url,
'link': item.link,
'description': item.description,
}
Title and link work for most of rss feeds, but image and description do not.
Since a lot of rss fees has image as html inside of description like this:
{ title: 'The Rio Olympics Are Where TV Finally Sees the Future',
description: '<div class="rss_thumbnail"><img src="http://www.wired.com/wp-content/uploads/2016/08/GettyImages-587338962-660x435.jpg" alt="The Rio Olympics Are Where TV Finally Sees the Future" /></div>Time was, watching the Olympics just meant turning on your TV. That\'s changed—and there\'s no going back. The post The Rio Olympics Are Where TV Finally Sees the Future appeared first on WIRED.',...
How can I get image's url from it?
EDIT:
http.get("http://www.wired.com/feed/"...
.on('readable', function() {
let stream = this;
let item;
while( item = stream.read()){
let article = {
'title': item.title,
'image': item.image.url,
'link': item.link,
'description': item.description,
}
news.push(article);
}
})
this is some of my codes, and basically I am trying to get image url from Wired rss.
If I user 'image': item.image.url, it does not work. So what should I change it to?
use xml2js for converting xml to json
var parseString = require('xml2js').parseString;
var xml = '<img title=\'A San Bernardino County Fire Department firefighter watches a helitanker make a water drop on a wildfire, seen from Cajon Boulevard in Devore, Calif., Thursday, Aug. 18, 2016. (David Pardo/The Daily Press via AP)\' height=\'259\' alt=\'APTOPIX California Wildfires\' width=\'460\' src=\'http://i.cbc.ca/1.3730399.1471835992!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_460/aptopix-california-wildfires.jpg\' />';
parseString(xml, function (err, result) {
console.log(JSON.stringify(result, null, 4));
console.log(result["img"]["$"]["src"]);
});
Use regex of string:
var res = description.match(/src=.*\.(jpg|jpeg|png|gif)/gi);
Fiddle Demo
One idea would be to use regular expressions. For ex:
var re = /(src=)(\\'htt.*\\')/g
var img_string = "your image tag string"
var match = re.exec(img_string)
var result = match[1]
You can use DOMDocument parser to get Image source.
$html = "<img title=\'A San Bernardino County Fire Department firefighter watches a helitanker make a water drop on a wildfire, seen from Cajon Boulevard in Devore, Calif., Thursday, Aug. 18, 2016. (David Pardo/The Daily Press via AP)\' height=\'259\' alt=\'APTOPIX California Wildfires\' width=\'460\' src=\'http://i.cbc.ca/1.3730399.1471835992!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_460/aptopix-california-wildfires.jpg\' />";
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/#src)"); # "/images/image.jpg"

Getting div data which has empty spaces in its class field [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a page that I need to parse which is :
<div class="shadowBox someOtherBox">
.
.
.
</div>
.
.
.
<div class="shadowBox other">
<h2>OTHERS</h2>
<ul>
<li>
TITLE #1
</li>
<li>
TITLE #2
</li>
<li>
TITLE #3
</li>
</ul>
</div>
I would like to get each link inside <div class="shadowBox other"> and its TITLE. I tried to do this in many different ways, but at the end I couldn't managed to do it. Here is the code for one of my tries;
function parse(crn)
{
request("LINK_OF_PAGE", function(error, response, html)
{
if(!error)
{
var $ = cheerio.load(html);
var title, news_url, url_hash;
var json = { title : "", news_url : ""};
var links = [];
var data = $('div').filter('.shadowBox').last();
//var data = $('.shadowBox.other').children('ul').children('li').children('a');
console.log(data);
news_url = data.prev().text();
url_hash = md5(news_url);
}
});
}
Why my logic doesn't work? How would I achieve what I want?
Looks like you are trying to populate the links array with the href and text value of anchor elemnets then
var links = $('.shadowBox.other li a').map(function(){
var $this = $(this);
return { title : $this.attr('href'), news_url : $this.text()}
}).get();

Function not working properly. Please help

Hello I'm having trouble with the function setUpTranslation().
//The purpose of this function is to place the French phrases into the document and set up the event handlers for the mousedown and mouseup events.
//These are the arrays of the French phrases and English phrases that I have do place into the document:
var english = new Array();
english[0] = "This hotel isn't far from the Eiffel Tower.";
english[1] = "What time does the train arrive?";
english[2] = "We have been waiting for the bus for one half-hour.";
english[3] = "This meal is delicious";
english[4] = "What day is she going to arrive?";
english[5] = "We have eleven minutes before the train leaves!";
english[6] = "Living in a foreign country is a good experience.";
english[7] = "Excuse me! I'm late!";
english[8] = "Is this taxi free?";
english[9] = "Be careful when you go down the steps.";
var french = new Array();
french[0] = "Cet hôtel n'est pas loin de la Tour Eiffel.";
french[1] = "A quelle heure arrive le train?";
french[2] = "Nous attendons l'autobus depuis une demi-heure.";
french[3] = "Ce repas est délicieux";
french[4] = "Quel jour va-t-elle arriver?";
french[5] = "Nous avons onze minutes avant le départ du train!";
french[6] = "Habiter dans un pays étranger est une bonne expérience.";
french[7] = "Excusez-moi! Je suis en retard!";
french[8] = "Est-ce que ce taxi est libre?";
french[9] = "Faites attention quand vous descendez l'escalier.";
//function I'm having trouble with
function setUpTranslation(){
var phrases = document.getElementByTagName("p");
for (i =0; i<phrases.length; i++){
phrases[i].number =i;
phrases[i].childNodes[1].innerHTML =french[i];
phrases[i].childNodes[1].onmousedown =function(){
swapFE(event);
phrases[i].childNodes[1].onmouseup =function(){
swapEF(event);
};
};
}
//Below are the other two functions swapFE() and swapEF(). The purpose of the function swapFE() is to exchange the French phrase for the English translation
//The purpose of the function swapEF() is to exchange the English translation for the French phrase.
function swapFE(e){
var phrase =e.srcElement;
var parent =phrase.parentNode;
var idnum =parent.childNodes[0];
var phrasenum =parseInt(idnum.innerHTML)-1;
phrase.innerText =english[phrasenum];
}
function swapEF(e){
var phrase =e.srcElement;
var parent =phrase.parentNode;
var idnum =parent.childNodes[0];
var phrasenum =parseInt(idnum.innerHTML)-1;
phrase.innerText =french[phrasenum];
}
//Not sure if these are right. Thanks in advance!
Assuming that your HTML looks like this
<p><span>1</span><span></span></p>
<p><span>2</span><span></span></p>
...
<p><span>10</span><span></span></p>
Then all you need to do is to add the curly bracket after swapFE(event); (points for Mr Plunkett) and replace getElementByTagName with getElementsByTagName (you're missing an 's' in there).
One additional thing to note: If the English phrase is shorter than the French, the container might shrink when the onmousedown event fires. If this shrinkage causes the mouse cursor to be positioned outside the container, the subsequent onmouseup event will not be triggered. Of course, if you are using block elements (e.g. a <div>) instead of my assumed <span>, that likely isn't an issue. In any case, it's probably better to attach the event listeners to the <p> tags instead.

Categories

Resources