I am relatively new to the developer community, and I am having trouble dealing with the & character when dealing with text.
To be specific, my twitterbot program stores the words of a tweet into an array, rearranges the array in alphabetical order, and posts the new alphabetized tweet text. I run into issues dealing with tweets that contain an ampersand. For example, let's say a tweet says "T & P". It will store an ampersand as:
['T', '&', 'P']
Therefore, when my program alphabetizes and posts a tweet, it will post: & P T
Basically, I just want to know how to display the ampersand as '&' in twitter, instead of &
.
Currently, I have been trying this:
for (i = 0; i < data.length; i++) {
tweetTxt = data[i].text;
if(tweetTxt.includes('&')) {
console.log("\nThis tweet reads: " + tweetTxt);
tweetTxt.replace(/&/g, '&');
console.log("\n" + tweetTxt);
}
What am I missing? How do I store an ampersand as '&' instead of &
so that way the posted tweet will show a true ampersand.
When you call .replace()
on a string, it creates a new string with the modifications and returns it in that statement. It doesn't modify the string that you called it on.
So you have to re-set the string to the result of the tweetTxt.replace()
statement.
for (i = 0; i < data.length; i++) {
tweetTxt = data[i].text;
if(tweetTxt.includes('&')) {
console.log("\nThis tweet reads: " + tweetTxt);
tweetTxt = tweetTxt.replace(/&/g, '&');
console.log("\n" + tweetTxt);
}
}