How to remove colon based emojis from text using javascript - javascript

How can i remove all instances of :smile: style emjois from a string using javascript? Here is an example below I got in JSON with :point_right: in it. I'd love to remove all of them from a string.
[ { service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299' }

Just use String.prototype.replace() with a regular expression:
const input = 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”';
const output = input.replace(/:\w+:/g, '');
console.log(output);

Assuming the emojis are all one word, between :s:
const obj = {
service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299'
}
obj.title = obj.title.replace(/:[^ ]+:/g, '');
obj.text = obj.text.replace(/:[^ ]+:/g, '');
console.log(obj);

From this answer Replacing values in JSON object you could do this :
var json=[ { service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299' }];
var rep = JSON.stringify(json).replace(/(“)(:[^:]+:)/g, '$1');
var New = JSON.parse(rep);
console.log(New);

Try this :
// JSON Object
var jsonObj = [{
"service_name": "Instagram",
"title": "Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”",
"text": "36 Likes, 2 Comments - “:point_right: Real people, making real products",
"ts": "1523497358.000299"
}];
// Replace :point_right: with blank string.
jsonObj.map(obj => {
obj.title = obj.title.replace(":point_right: ", "");
obj.text = obj.text.replace(":point_right: ", "");
return obj;
});
// Output
console.log(jsonObj);

Related

splitting an string list with proper aligning the string elements

Example Company 1,company ltd 2,company, Inc.,company Nine nine, ltd,company ew So here is example of the string, I want to split it like that it consider Company 1 as one company and company, Inc. as one, but here got situation in company, Inc. it condidering 2 companies while this logic. how can I resolve this? Lke with such strings company, Inc. I want to consider it one element only
const company = company.split(",");
Here the string can be anything, this is just example for the string, but it can be any name. So I am looking for generic logic which works for any string, having same structure of string.
Note $ ==(,) represents as separation point, kept to get clarity that from that point I need to separate the string
Object:
Example 1
{
_id: 5de4debcccea611e4d14d4d5
companies: One Bros. Inc. & Might Bros. Dist. Corp.$Pages, Inc.$Google Inc. Search$Aphabet Inc. tech.
}
Example 2
{
_id: 5de4debccc333611e4d14d4f5
companies: Google Comp. Inc.$Google Comp. Inc. Estd.$Tree, Ltd.$Tree, Ltd.
}
First I split on 'ompany' rather than 'company', because you have one instance of 'Company' with a capital C -- see the output of the first console log within a comment below.
Then I put things back together using reduce -- map is not the right choice here, as I need an array that is one fewer than the size of the fragments I generated. Then though since I need an array that corresponds to the number of strings we want to return, which is one fewer than the number of fragments, the first thing I do inside my reduce is ensure I do not look beyond the end of the array.
Then I split each fragment and pop off the last element, which just puts either "C" or "c" back together with "ompany". Then I replace any trailing ',c' from the next fragment with an empty string, and add the result to the company. Finally I add the entire result to the array I'm generating with reduce. See comment results at bottom. Also here it is on repl.it: https://repl.it/#dexygen/splitOnCompanyStringLiteral
This is a fairly concise way to do this but again if you can do anything to improve your data, you won't have to use such unnecessarily complicated code.
const companiesStr = "Company 1,company ltd 2,company, Inc.,company Nine nine, ltd,company ew";
const companySuffixFragments = companiesStr.split("ompany");
console.log(companySuffixFragments);
/*
[ 'C', ' 1,c', ' ltd 2,c', ', Inc.,c', ' Nine nine, ltd,c', ' ew' ]
*/
const companiesArr = companySuffixFragments.reduce((companies, fragment, index, origArr) => {
if (index < companySuffixFragments.length - 1) {
let company = fragment.split(',').pop() + 'ompany'
company = company + origArr[index + 1].replace(/,c$/, '');
companies.push(company);
}
return companies
}, []);
console.log(companiesArr);
/*
[ 'Company 1',
'company ltd 2',
'company, Inc.',
'company Nine nine, ltd',
'company ew' ]
*/
First change , with any other symbol. I am using & here and then split string with ,
var str= 'Company 1,company ltd 2,company, Inc.,company Nine nine, ltd,company ew';
str = str.replace(', Inc.','& Inc.');
/*str = str.replace(', ltd','& ltd');*/
console.log(str.split(',').map((e)=>{return e.replace('&',',').trim()}));
try with the below solution.
var str = ["company 1","company ltd 2","company", "Inc.","company Nine nine", "ltd","company ews"];
var str2 =str.toString()
var str3 = str2.split("company")
function myFunction(item, index,arr){if(item !=""){let var2 = item.replace(/,/g," ");var2 = "Company"+var2;arr[index]=var2;} }
str3.forEach(myFunction)
OUtput:
str3
(6) ["", "Company 1 ", "Company ltd 2 ", "Company Inc. ", "Company Nine nine ltd ", "Company ews"]
And remove the first element of the array.
As has been commented I'd try to get a more clean String so that you don't have to write "strange" code to get what you need.
If you can't do that right now this code should solve your problem:
let string = 'Company 1,company ltd 2,company, Inc.,company Nine nine, ltd,company
ew';
let array = string.split(',');
const filterFnc = (array) => {
let newArr = [],
i = 0;
for(i = 0; i < array.length; i++) {
if(array[i].toLowerCase().indexOf('company') !== -1) {
newArr.push(array[i]);
} else {
newArr.splice(newArr.length - 1, 1, `${array[i - 1]}, ${array[i]}`);
}
}
return newArr;
};
let filteredArray = filterFnc(array);

Set HTML elements to random object key:value pairs

I'm trying to use the "database" I have made to cycle through some the quotes at random when the button is clicked and changing the existing quote in the HTML to the random quote and the existing author in the same way
var myDatabase = [
{quote:"I have learned silence from the talkative...", author:"Khalil Gibran"},
{quote: "One of the blessings of old friends that you can afford to be stupid with them." author:"Ralph Waldo Emmerson"},
{quote: "Once we accept our limits, we go beyond them." author:"Albert Einstein"}
];
var newQuote = document.getElementById('displayedQuote');
var newAuthor = document.getElementById('author');
$("#quoteButton").click(function() {
var rand = Math.floor(Math.random()*database.length)
newQuote = myDatabase.[rand].quote;
newAuthor = myDatabase.[rand].author;
});
Firstly your "Database" has syntax errors. It should read:
var myDatabase = [{
"quote": "I have learned silence from the talkative...",
"author": "Khalil Gibran"
}, {
"quote": "One of the blessings of old friends that you can afford to be stupid with them.",
"author": "Ralph Waldo Emmerson"
}, {
"quote": "Once we accept our limits, we go beyond them.",
"author": "Albert Einstein"
}];
Secondly, you're mixing vanilla JS with Jquery. Whilst this isn't technically wrong it's much easier to read if you just stick to one or the other
var newQuote = $('#displayedQuote');
var newAuthor = $('#newAuthor');
Lastly, the syntax in your click method is incorrect. You're assigning a value to the newQuote and newAuthor variables rather than manipulating the element. What you want to do is use the .text() method to add the object values to the DOM.
Also, you don't need the dot notation before the [rand] integer and you want myDatabase.length not database.length
$("#quoteButton").click(function() {
var rand = Math.floor(Math.random() * myDatabase.length)
newQuote.text(myDatabase[rand].quote)
newAuthor.text(myDatabase[rand].author)
});
Here's a working example: https://codepen.io/mark_c/pen/pExxQA
Something like that ?
var myDatabase = [
{quote:"I have learned silence from the talkative...", author:"Khalil Gibran"},
{quote: "One of the blessings of old friends that you can afford to be stupid with them." author:"Ralph Waldo Emmerson"},
{quote: "Once we accept our limits, we go beyond them." author:"Albert Einstein"}
];
var newQuote = document.getElementById('displayedQuote');
var newAuthor = document.getElementById('author');
$("#quoteButton").click(function() {
var rand = Math.floor(Math.random()*database.length)
$(newQuote).text(myDatabase[rand].quote);
$(newAuthor).text(myDatabase[rand].author);
});

Multiple words search and calculation algorithm (Angular/Javascript)

I'm loading json file from database with two fields words and grade. Each word is graded for example true has 1 while lie has -1. Then i take input from text filed and i need to grade it based on grades from JSON file and then calculate score by summarizing the grades, but i just can't seem to find the way to do that. Words that are not in file are not being calculated.
I tried string.search match but it's to complicated and in the end i couldn't get result the way i wanted. I tried array searches same thing. I searched for on line solution, but no one has done anything similar so i can't copy it.
JSON
[
{"word":"true","grade":1},
{"word":"hate","grade":-1},
{"word":"dog","grade":0.8},
{"word":"cat","grade":-0.8}
]
String
"Dogs are wonderful but i prefer cats, cats, i can not lie although dog is a true friend".
The first thing I'd do is turn your JSON data into a map which can easily be searched - key would be the word, and value the grade:
var json = [
{"word":"true","grade":1},
{"word":"hate","grade":-1},
{"word":"dog","grade":0.8},
{"word":"cat","grade":-0.8}
];
var map = json.reduce(function(p,c){
p.set(c.word.toLowerCase(),c.grade);
return p;
}, new Map());
console.log(...map);
Then, its just a case of splitting your string, whilst also calculating the total score - again reduce can be used
var json = [
{"word":"true","grade":1},
{"word":"hate","grade":-1},
{"word":"dog","grade":0.8},
{"word":"cat","grade":-0.8}
];
var map = json.reduce(function(p,c){
p.set(c.word.toLowerCase(),c.grade);
return p;
}, new Map());
var input = "Dogs are wonderful but i prefer cats cats i can not lie although dog is a true friend";
var score = input.split(' ').reduce(function(p,c){
var wordScore = map.get(c.toLowerCase()) || 0;
return p + wordScore;
},0);
console.log(score);
Note that I have manually removed punctuation in the above input - I'll leave that as an exercise for you.
Also note that "cats" != "cat" so some of your words wont be found!
Let's first think of the algorithm. Two options:
Search and count the input string as many times as number of words in your JSON, or
Check each word in your input string against the JSON contents.
Since the JSON length is known and (I presume) shorter than the possible input string, I would tend to prefer option 2.
Now, after selecting option 2, you need to split the input string into words and create an array containing one word each entry of the array.
You can achieve this using the mystring.split(" ") method. This, of course, does not take into account punctuations, but you can handle this using the same method.
Now, you can add to each entry in your JSON a field to count the number of appearances of each entry in the JSON within the string.
Finally, you sum the product of the counters and the grade.
console.log((function(rules, str) {
var sum = 0;
Array.prototype.forEach.call(rules, function(rule) {
var match = str.match(rule.regexp);
match && (sum += str.match(rule.regexp).length * rule.grade);
console.log([rule.regexp, match&&match.length, rule.grade, match&&match.length * rule.grade, sum]);
});
return sum;
})([{
"regexp": /true/g,
"grade": 1
}, {
"regexp": /hate/g,
"grade": -1
}, {
"regexp": /dog/g,
"grade": 0.8
}, {
"regexp": /cat/g,
"grade": -0.8
}], "Dogs are wonderful but i prefer cats, cats, i can not lie although dog is a true friend"));
i use regexp rather than string, u can use string and convert to regex at run time, hope this would help

Javascript: merge two arrays into single object without losing key order

I have some raw imdb data in two strings:
var headers = "ID imdbID Title Year Rating Runtime Genre Released Director Writer Cast Metacritic imdbRating imdbVotes Poster Plot FullPlot Language Country Awards lastUpdated";
const content = "1 tt0000001 Carmencita 1894 NOT RATED 1 min Documentary, Short William K.L. Dickson Carmencita 5.8 1136 http://ia.media-imdb.com/images/M/MV5BMjAzNDEwMzk3OV5BMl5BanBnXkFtZTcwOTk4OTM5Ng##._V1_SX300.jpg Performing on what looks like a small wooden stage, wearing a dress with a hoop skirt and white high-heeled pumps, Carmencita does a dance with kicks and twirls, a smile always on her face. USA 2016-05-04 00:03:31.600000000";
Of course I am cleaning out the tabs and spaces etc and creating two arrays like so:
const values = content.split(/(\t+)/).filter( (part) => !/\t/.test(part) );
let keys = headers.split(/(\s+)/).filter( (part) => !/\s+/.test(part) );
Now I want to map the keys in keys array to the values in the values array accurately. So I do a reduce like so:
var result = {};
values.reduce( (acc, val, index) => {
return result[ keys[index] ] = val;
}, result);
This gives me back a final result object that looks like this:
{
Cast: "1136",
Director: "Carmencita",
Genre: "Documentary, Short",
ID: "1",
imdbID: "tt0000001",
imdbRating: "Performing on what looks like a small wooden stage, wearing a dress with a hoop skirt and white high-heeled pumps, Carmencita does a dance with kicks and twirls, a smile always on her face.",
imdbVotes: "USA",
Metacritic: "http://ia.media-imdb.com/images/M/MV5BMjAzNDEwMzk3OV5BMl5BanBnXkFtZTcwOTk4OTM5Ng##._V1_SX300.jpg",
Poster: "2016-05-04 00:03:31.600000000",
Rating: "NOT RATED",
Released: "William K.L. Dickson",
Runtime: "1 min",
Title: "Carmencita",
Writer: "5.8",
Year: "1894"
}
As you can see, the order is all mixed up! How do I get the right order in my data so I get title key mapped to the movie title value etc. ?
I am open to using a library like lodash to achieve this but can't tell what I should use? Here is a jsbin demo of the present state: https://jsbin.com/gekawi/edit?js,console
If you take the raw data with the tabs inside, you could use them for splitting.
var headers = "ID imdbID Title Year Rating Runtime Genre Released Director Writer Cast Metacritic imdbRating imdbVotes Poster Plot FullPlot Language Country Awards lastUpdated",
content = "1 tt0000001 Carmencita 1894 NOT RATED 1 min Documentary, Short William K.L. Dickson Carmencita 5.8 1136 http://ia.media-imdb.com/images/M/MV5BMjAzNDEwMzk3OV5BMl5BanBnXkFtZTcwOTk4OTM5Ng##._V1_SX300.jpg Performing on what looks like a small wooden stage, wearing a dress with a hoop skirt and white high-heeled pumps, Carmencita does a dance with kicks and twirls, a smile always on her face. USA 2016-05-04 00:03:31.600000000",
headerArray = headers.split(/\t/),
contentArray = content.split(/\t/),
object = {};
headerArray.forEach(function (k, i) {
object[k] = contentArray[i];
});
console.log(object);

Break up a string in JS

I have a script built to grab a quote from an array at random, and display it.
I'm trying to format it so it would split the quote and the author like so:
"Insert quote"
Name of person saying Quote
I've tried using split with \n and <br /> and nothing works, even in an alert.
here is my code:
//Initalize the array
var quotes = [];
//Insert data into the array
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
quotes[1] = "Video games are bad for you? That's what they said about rock n' roll." + "Shigeru Miyamoto";
quotes[2] = "I'd like to be known as the person who saw things from a different point of view to others." + "Shigeru Miyamoto";
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
quotes[4] = "The future was uncertain, absolutely, and there were many hurdles, twists, and turns to come, but as long as I kept moving forward, one foot in front of the other, the voices of fear and shame, the messages from those who wanted me to believe that I wasn't good enough, would be stilled." + "Chris Gardner";
quotes[5] = "Running a start-up is like eating glass. You just start to like the taste of your own blood." + "Sean Parker";
quotes[6] = "I used to drink cristal, the muh'fucker's racist. So I switched gold bottles on to that Spade shit" + "Shawn Carter (Jay Z)";
quotes[7] = "I think it's better to let my work do the talking" + "Shigeru Miyamoto.";
quotes[8] = "Success is a lousy teacher. It seduces smart people into thinking they can't lose." + "Bill Gates";
quotes[9] = "We need to reengineer companies to focus on figuring out who the customer is, what's the market and what kind of product you should build." + "Eric Ries";
quotes[10] = "I have no friends and no enemies - only competitors." + "Aristole Onassis";
quotes[11] = "Working 24 hours a day isn't enough anymore. You have to be willing to sacrifice everything to be successful, including your personal life, your family life, maybe more. If people think it's any less, they're wrong, and they will fail." + "Kevin O'Leary";
quotes[12] = "My hope is to the see the benefits of my labour spread out in the community." + "W. Brett Wilson";
quotes[13] = "I'm not here to make friends; I'm here to make money." + "Kevin O'Leary";
quotes[14] = "Good artists copy, great artists steal" + "Pablo Picasso";
quotes[15] = "Welcome ladies and gentlemen to the eighth wonder of the world. The flow of the century, always timeless; HOV!" + "Shawn Carter (Jay Z)";
quotes[16] = "Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel";
quotes[17] = "I believe life is an intelligent thing: that things aren't random." + "Steve Jobs";
quotes[18] = "Pretty? You mean like rainbows, unicorns, and sparkles?" + "Michelle Brown";
quotes[19] = ".....and for that reason, I'm OUT!" + "Mark Cuban";
//Splits the quote into two pieces, the quote and the person.
var quoteSplit = function (quotes) {
var split = quotes.split("+").replace("\n");
}
//Displays a quote from the array at random.
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote);
//END
When you're building your array, you are concatenating the quote with the author. So this:
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
Ends up with this string being set to quotes[0]
It doesn't matter how many times you have failed, you only have to be right once.Mark Cuban
And your split statement will not work, because the + is not included in the string. This isn't a great way of setting up your array, though. What happens if your quote contains the + symbol, for example?
A better way would be to create an object for each item:
quotes[0] = {
text: "It doesn't matter how many times you have failed, you only have to be right once.",
author: "Mark Cuban"
}
Then you can do:
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote.text + '<br>' + displayQuote.author);
It's seems that + sign is not in your string. The following code:
console.log("Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel");
will return to you string
Today’s “best practices” lead to dead ends; the best paths are new and untried.Peter Thiel;
So, you just have to include + sig in your strings like that:
"Today’s “best practices” lead to dead ends; the best paths are new and untried.+Peter Thiel"
As Daniel A. White said in the comments section. You are considering + to be part of the string but you are in fact concatenating 2 strings on each index.
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
should be:
quotes[3] = "Stay hungry, stay foolish, stay crazy.+Steve Jobs";
Or you could use regex ( Unfortunately I can't provide a regex example right now ) but those are two of your possible options.
If you output any element of your array, you'll see that each entry is a single string with quote and person. Ex.
console.log(quotes[3]);
Stay hungry, stay foolish, stay crazy.Steve Jobs
That's because + concatenates when applied to strings.
As suggested in the comments, you could use split on punctuation marks, although that would break some of your quotes.
You could do something like
quotes[3]=["Stay hungry, stay foolish, stay crazy.","Steve Jobs"];
and output each element separately.
Try this:
var quotes = {
1: {
quote: 'Hello world.',
author: 'Test test'
},
2: {
quote: 'Hello world 2.',
author: 'Test test 2'
},
};
// Display random quote
function displayQuote(){
var key = Math.floor(Math.random() * Object.keys(quotes).length + 1);
return quotes[key].quote + ' ' + quotes[key].author;
};
document.write(displayQuote());

Categories