Remove concatenated strings Javascript - javascript

I'm working with the Twitter API and I'm trying to get only the first news of a tweet and its link. If I console.log tweetNews I get something like this as example:
{
text: 'exampletext. \n' +
'\n' +
'exampletext. \n' +
'\n' +
'https://examplelink',
href: 'https://examplelink
},
I would like to get only the first string of the text, removing also the link inside the text.
Down below the rest of my code:
module.exports.filterTweets = (parsedArray) => {
const filteredTweets = parsedArray.filter(
(tweet) => tweet.entities.urls.length === 1
);
const tweetNews = filteredTweets.map((x) => {
return { text: x.full_text, href: x.entities.urls[0].url };
});
console.log("tweetNews", tweetNews);
return tweetNews;
};

I'm not sure I 100% follow what you are asking for, but this should get you on your way. This shows how to get the first part of the string (up to the first line break), and how to remove (http/https) URLs:
function cleanInput(input){
let firstLine = input.split(/\s+\n\s+/)[0]
//this regex is overly simplistic, just for demo purposes
//see more complete example at https://stackoverflow.com/a/3809435/57624
let withoutURL = firstLine.replace (/http[s]?:\/\/[a-z./]+/i, '');
return withoutURL
}
let sampleData1 = {
text: 'exampletext. \n' +
'\n' +
'exampletext. \n' +
'\n' +
'https://examplelink',
href: 'https://examplelink'
};
let sampleResult1 = cleanInput(sampleData1.text)
console.log("result 1: " + sampleResult1)
let sampleData2 = {
text: 'A URL: https://examplelink.com \n' +
'\n' +
'exampletext. \n' +
'\n' +
'more',
href: 'https://examplelink'
};
let sampleResult2 = cleanInput(sampleData2.text)
console.log("result 2: " + sampleResult2)

Related

Get full word containing a specific element

Having the reference to a specific DOM element (e.g. <mark>), how can we get the full word containing that element?
For example :
H<mark>ell</mark>o Wor<mark>l</mark>d, and He<mark>llo</mark>, <mark>Pluto</mark>!
I expect to get the following output :
First <mark>: Hello
Second: World
Third: Hello
Fourth: Pluto
var $marks = $("mark");
var tests = [
"Hello",
"World",
"Hello",
"Pluto",
];
function getFullWord($elm) {
// TODO: How can I do this?
// This is obviously wrong.
return $elm.html();
}
var $marks = $("mark");
tests.forEach(function(c, i) {
var word = getFullWord($marks.eq(i));
if (word !== c) {
alert("Wrong result for index " + i + ". Expected: '" + c + "' but got '" + word + "'");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
H<mark>ell</mark>o Wor<mark>l</mark>d, and He<mark>llo</mark>, <mark>Pluto</mark>!
If you need fast and compact code (one-liner), try this:
var $marks = $('mark');
$marks.each(function() {
var wholeWord = (this.previousSibling.nodeValue.split(' ').pop() +
this.textContent +
this.nextSibling.nodeValue.split(' ')[0]
).replace(/[^\w\s]/gi, '');
});
JSFiddle (with logging into console and comments)

Pass JavaScript Function in href

I am working on VS2103 Cordova App. I have created list of items. I want to pass data to another page when i press on item. I've created this list by jQuery.
Here is my code :
for (var i = 0; i < data.length; i++) {
if ((Provider == "Doctors")) {
$("#list").append('<li class="list-message" ><a class="w-clearfix w-inline-block" href="javascript:ProviderDetails(' + data[i].DoctorName + ',' + data[i].DoctorAddress + ',' + data[i].DoctorPhone + ',' + data[i].DoctorPhone2 + ',' + data[i].DoctorPhone3 + ',' + data[i].DocLat + ',' + data[i].DocLong + ',' + data[i].DoctorNotes + ',' + data[i].Category + ');" data-load="1"><div class="w-clearfix column-left"><div class="image-message"><img src="images/Doctors.png"></div></div><div class="column-right"><div class="message-title">' + data[i].DoctorName + '</div><div class="message-text">' + data[i].DoctorAddress + '</div></div></a></li>');
}
}
And here is my function :
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category) {
localStorage.setItem("Name", Name);
localStorage.setItem("Address", Address);
localStorage.setItem("Tel", Tel);
localStorage.setItem("Phone2", Phone2);
localStorage.setItem("Phone3", Phone3);
localStorage.setItem("Lat", Lat);
localStorage.setItem("Lang", Lang);
localStorage.setItem("Notes", Notes);
localStorage.setItem("Category", Category);
window.location.href = "../Details.html";
}
It doesn't do any thing when i press any items . Any help ?
Pay attention on how you build the string:
href="javascript:ProviderDetails(' + data[i].DoctorName + ',' ......
you need to add the string delimiters:
href="javascript:ProviderDetails(\'' + "data[i].DoctorName" + '\',\'' .....
Your function is declared as:
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category)
{
....
}
Now, because your function expects strings as input you can call your function as:
ProviderDetails('string1', 'string2', .....)
Your javascript loop instead produces:
ProviderDetails(string1, string2, .....)
For javascript now the parameters are considered as variables, i.e., string1 is no more a string but a value contained in the variable string1.
But because you do not have such a variable your function call does not work.
So, the delimiters are important to instruct js to understand the beginning and end of a string.
As a delimiter you can you the symbols: ' or ".
But you need to escape the delimiter itself if you want to use it inside the strings:
var a = 'this isn't a string'; // wrong because the inner delimiter is not escaped.
var a = 'this isn\'t a string'; // OK because the inner delimiter is escaped
Of course if you use inside the string the other delimiter you do not need to escape it.
var a = "this isn't a string"; // this is OK

Check if a string contains one of the strings in array

I'm trying to check if the team contains one of the following strings in the array. If yes then remove it. Why is it not doing this?
function changeName(name) {
var team = name;
var removearray = ['.CS', ' Dota2', '-Dota2', ' Esports', 'eSports', ' Tactics', 'DotCom', ' DotA2', ' - LoL', '-LoL', ' Carry', 'Â', ' LoL'];
removearray.forEach(function( word ) {
team = team.replace( new RegExp( word, 'g' ), '' );
});
return team;
}
Please note that "forEach" is not supported in certain browsers such as IE8.
Also, please consider the following implementation:
function changeName(name) {
var removearray = ['.CS', ' Dota2', '-Dota2', ' Esports', 'eSports', ' Tactics', 'DotCom', ' DotA2', ' - LoL', '-LoL', ' Carry', 'Â', ' LoL'];
return team = removearray.reduce(function(previous, current) {
return previous.replace( new RegExp( current, 'g' ), '' );
}, name);
}
The "reduce" method available in the Array Prototype in Javascript is a very nice way of doing tasks such as this one.
function changeName(name) {
var team = name;
var removearray = ['.CS', ' Dota2', '-Dota2',
' Esports', 'eSports', ' Tactics', 'DotCom',
' DotA2', ' - LoL', '-LoL', ' Carry', 'Â', ' LoL'];
for(var i = 0; i < removearray.length; i++){
while(team.indexOf(removearray[i]) > -1) {
var index = team.indexOf(removearray[i]);
if (index > -1) {
team = team.substr(0, index) +
team.substr(index + removearray[i].length);
}
}
}
return team;
}
var one = changeName('John'); // returns 'John'
var two = changeName('John Dota2 Doe'); // returns 'John Doe'
var three = changeName('John Dota2 Doe Dota2.CS') // returns 'John Doe'

go to the next index of an array using onclick in Javascript

I apologize in advance if I'm vague or my code is difficult to understand, I'm still learning this stuff. I'm trying to display information that is stored within an array. I want to display this information when a button is clicked and when it is clicked again, the next index in the array displays its information..
I need help setting up a function that advances to the next index of the array. Thanks!
(function(){
var students =[ //array of information
{name:'john',
address:{
address:'821 Imaginary St',
city:'Chicago',
state:'Il'},
gpa:[4.0,3.5,3.8]},
{name:'jim',
address:{
address:'127 fake Rd',
city:'Orlando',
state:'Fl'},
gpa:[2.5,3.3,3.6]}];
var redBut = document.querySelector('.buttonred');
redBut.onclick = getInfo;
var count = 0;
function getInfo(){
var stn = students[0];
if(count<3){
count++;
document.getElementById('name').innerHTML = 'Name: ' + stn.name; //this is what is to be displayed when the button is clicked
document.getElementById('address').innerHTML = 'Address: ' + stn.address.address + " " + stn.address.city + ", " + stn.address.state;
document.getElementById('gpa').innerHTML = 'GPA: ' + stn.gpa[0] +", " + stn.gpa[1] + ", " + stn.gpa[2];
document.getElementById('date').innerHTML = 'Date: ' + d.toLocaleDateString();
document.getElementById('gpaavg').innerHTML = 'Average GPA: ' + gpas;
}
}
I think you want: var stn = students[count];
And not: var stn = students[0];
(DOH!)

What is the optimal way to load form data into a string and then to localStorage?

Is this the optimal way to load form data into a string and then to localStorage ?
I came up with this on my own, and I am not good in programming. It works, for what I need, but I am not sure if it's a bulletproof code?
<script>
var sg = document.getElementById("selectedGateway");
var sd = document.getElementById("selectedDestination");
var dm = document.getElementById("departureMonth");
var dd = document.getElementById("departureDay");
var dy = document.getElementById("departureYear");
var rm = document.getElementById("returnMonth");
var rd = document.getElementById("returnDay");
var ry = document.getElementById("returnYear");
var ad = document.getElementById("adults");
var ch = document.getElementById("option2");
$("#searchRequestForm").submit(function() {
var string = 'From: ' + sg.value + ' \nTo: ' + sd.value + ' \nDeparture: ' + dm.value + '/' + dd.value + '/' + dy.value + ' \nReturn: ' + rm.value + '/' + rd.value + '/' + ry.value + ' \nNumber of adults: ' + ad.value + ' \nNumber of children: ' + ch.value;
localStorage.setItem("string", string);
});
</script>
I would use something like the following so that I could deal with an object and its properties rather than a big string. Note that other than the jQuery selectors, this is pure JavaScript.
Demo: http://jsfiddle.net/grTWc/1/
var data = {
sg: $("#selectedGateway").val(),
sd: $("#selectedDestination").val()
// items here
};
localStorage.setItem("mykey", JSON.stringify(data));
To retrieve the data:
var data = JSON.parse(localStorage["mykey"]);
alert(data.sg);
See Also:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
http://api.jquery.com/jQuery.parseJSON/
I prefer a table driven approach so there is no repeated code (DRY):
var ids = [
"selectedGateway", "From: ",
"selectedDestination", "\nTo :",
"departureMonth", "\nDeparture: ",
"departureDay", "/",
"departureYear", "/",
"returnMonth", " \nReturn: ",
"returnDay", "/",
"returnYear", "/",
"adults", " \nNumber of adults: ",
"option2", " \nNumber of children: "];
var submitStr = "";
for (var i = 0; i < ids.length; i+=2) {
submitStr += ids[i+1] + document.getElementById(ids[i]).value;
}
localStorage.setItem("string", submitStr);
You could define a function such as the one below to directly get the values by id so then it would be simpler when you build your string.
function form(id) {
return document.getElementById(id).value;
}

Categories