how can you take out extra space in Javascript? - javascript

I'm trying to give a welcome message to recruiters that view my html webpage. The javascript code I'm using is:
function myFunction() {
var person = prompt("Please enter your name", "");
if (person == null) {
var message = document.getElementById("demo").innerHTML =
"Hello! Thank you for viewing my resume.";
message.innerHTML.replace((/\s/g,''));
}
else {
document.getElementById("demo").innerHTML =
"Hello " + person + "! Thank you for viewing my resume.";
}
}
The output in the html looks like Hello ! Thanks for viewing my resume. I've tried flipping the else and if outputs but it still adds the extra space. How can I fix this? I know there are similar questions on stack but the solutions haven't worked in my case. Thanks for your help.

in this case I think you can use Template literals (Template strings), one feature of ES6.
function myFunction() {
const person = prompt("Please enter your name", "");
if (!person) {
const message = document.getElementById("demo").innerHTML =
"Hello! Thank you for viewing my resume.";
message.innerHTML.replace((/\s/g,''));
}
else {
document.getElementById("demo").innerHTML =
`Hello ${person}! Thank you for viewing my resume.`;
}
}

The input would be labeled as Undefined which does not necessarily equal Null in JavaScript. My advice would be try creating a different way to check the name. Perhaps just give them the option "Continue as Guest" instead of checking for an empty value.

message.innerHTML.replace((/\s/g,''));
That line is doing absolutely nothing, replace() returns a new string, it doesn't modify the old one
And even if it replaced the old one, the desired output wouldn't really be what you're looking for, it would remove all spaces in the string, all of them.
The way you remove extra spaces is by using .trim(), trim() removes any extra spaces at the start and/or at the end of the string, so you would do: message.innerHTML = message.innerHTML.trim();
if (person == null) {
This wouldn't work, since prompt would return an empty string if the user didn't provide anything and your explicitly checking if it is equal to null instead, the most "optimal" way for checking for that, is as #Anh Tuan did, if (!person), this works because empty strings, undefined, or null all are falsy, so this is a nice way to check for all of them.

use:
if (!person)
instead of:
if (person == null)
and it should work fine. Everything else can stay the same.

Related

Use specific codewords as arguments/prefixes in a message?

I'm working in JavaScript with discord.js#v12. I asked this question in their support Discord, but due to issue in question being more related to JavaScript than Discordjs, here I am!
Let's get on it. I would like to fill out a RichEmbed in one single message. This RichEmbed will include a title, a description and 1 field. There can be more than one field in RichEmbeds, so I want to get it clear I only need 1.
Now, I realize I could do this using the following ways a) using awaitMessages and filling in the info one message at a time b) Separating arguments in the message with a space and making each argument text-like-this c) Separating arguments in the message with a newline and making each line a full argument. However, neither of these look very appealing to me. I also have a few people who are going to use my command who are not very technical and thus may not understand the usage of the command unless having a very detailed explanation, which is not very efficient when I'm not available.
I've used a) in the past and it's proven rather unefficient in a fast workflow, and b is straight up useless if I require a long description with a lot of sentences. C is usable but, again, there will be people using this command who are not technically "capable" and thus may struggle on their own. I want to make this as fluent as I can.
I also tried this method, which I found fairly useful but can be confusing:
/commandname Separating title / Description and / Field by a forward slash
So I came to the conclusion I want my syntax looking something like this:
/commandname title:My title! desc:This is the description field1:Field 1 and its title
EDIT: I spent a bit of research after posting, and found out I can use replace method to get the above result. This is currently my code:
let embed_title
let embed_desc
let embed_field
let firstarg = args[1]
if (firstarg.includes(`title:`)) {
var split = firstarg.replace(`title:`, ``)
embed_title = split
// expected output with "/commandname title:Testing123!": /commandname Testing123!
} else if (firstarg.includes(`desc:`)) {
var split = firstarg.replace(`desc:`, ``)
embed_desc = split
// expected output with "/commandname desc:Testing123!": /commandname Testing123!
} else if (firstarg.includes(`field:`)) {
var split = firstarg.replace(`field:`, ``)
embed_field = split
// expected output with "/commandname field:Testing123!": /commandname Testing123!
}
With this I can easily replace the first argument that has title:, desc: or field: in it, however I'd like to scour through the whole message (message.content). After that, I want to find which argument has title: in it. Then I want to feed every argument after title until it hits desc:. Repeat that until field is covered.
I solved my question by using a different syntax.
Instead of using /command and then:
title:Title of message desc:Description of message field1:Field of message
I'm using /command and then:
title Title of new message
description Description of new message
field Field 1 of new message
I'm splitting the arguments by newline \n instead of space/whitespace.
const msgArray = message.content.split(/ +/g)
const args = message.content.slice(prefix.length + msgArray[0].length).trim().split(`\n`)
Since I'm splitting the arguments by newline, it allows me to use spaces in my arguments without worrying about them coming out weird.
I then check for each argument and if it begins with Title, Description or Field, or none of them. Then, I iterate through each argument (from 1 to 3 in human terms) and check if they start with any of the three, then go from there. Note that this is manual and does not have superb compatibility if I wish to add another field or an image, but this works for my case and thus, I've solved it for now.
I realized this afternoon that I can simply loop through all the args and find which one contains a certain keyword. In the process, I can also filter out anything that does not match certain keyword(s).
Complete code as follows:
var _title = ``
var _desc = ``
var _fieldvalue = ``
var _useless = ``
args.forEach((element, i) => {
i += 1
if (element.startsWith(`description `)) {
_desc = element.slice(12)
}else if (element.startsWith(`title `)) {
_title = element.slice(6)
}else if (element.startsWith(`field `)) {
_fieldvalue = element.slice(6)
}else{
_useless = element
}
})
if (!_title && !_desc) return message.channel.send(`Please include at least a title or a description by using \`title\` or \`description\`.`)
if (!_fieldvalue) {
message.channel.send({embed: {
title: _title || null,
description: _desc || null,
}})
} else {
message.channel.send({embed: {
title: _title || null,
description: _desc || null,
fields: [
{
name: `\u200b`,
value: _fieldvalue,
},
],
}})
}
For those of you who want to see the code for the original result, see this pastebin result.

How to check and remove extra white spaces from a string during condition check

if (userResponseField.value.toUpperCase().includes('MY NAME IS ') === true || userResponseField.value.toUpperCase().includes('MY NAME\'S ') === true) {
What I am basically trying to do is create some sort of chatbot and it's working perfectly, it's just that it gets confused by extra whitespaces. How can I remove them during the condition check? I've looked for answers but none of them worked with the condition, they are still correct though, just not working with the way I want to do this whole thing. Note: I don't want the condition to make changes to the string/variable itself.
You could use regex:
if (userResponseField.value.match(/my\s+name(\s+i|')s/gi))
This returns true for inputs such as ' My name is '.
let predicate = str => !!str.match(/my\s+name(\s+i|')s/gi);
[
'my NaME iS ',
'my NaME\'s',
'my name s',
'my ame is',
'my nameis',
].forEach(input => console.log(input, ':', predicate(input)));
Have a look on trim :
if (
userResponseField.value.toUpperCase().trim().includes('MY NAME IS') === true ||
userResponseField.value.toUpperCase().trim().includes('MY NAME\'S') === true
) {
You can use String.prototype.trim() on both the value and the hard-coded string:
var userResponseField = {};
userResponseField.value = 'MY NAME IS';
if (userResponseField.value.toUpperCase().trim().includes('MY NAME IS '.trim()) === true || userResponseField.value.toUpperCase().trim().includes('MY NAME\'S '.trim()) === true) {
console.log("true");
}
it's me again.
I found a clever way to do this and if some of you, in the future, have this problem and have just found this thread, here is how I solved my problem:
var userResponseFieldOutput = userResponseField.value;
userResponseField.value = userResponseField.value.replace(/\s+/g, ' ');if
Since this code, along with the condition I have posted above are stored in a function, the userResponseFieldOutput is what I am going to use for outputting the user's messages in the chatbox. It remains unedited, while the userResponseField.value has its spaces removed.
For example:
chatResponse(userResponseFieldOutput, "Hi, " + userName);
Ignore the userName variable, it is part of the code that doesn't have to be shown right now. This is another function I have made, the first value is what appears in the chat on the right side, where the user's responses are shown. The string and the variable after the comma are what appears on the left side of the chat, where the chatbot's messages are shown. But as you can see, I don't use userResponseField.value. Instead, I am using userResponseFieldOutput, which will print the user's output without the extra white spaces being removed.
I hope I have been useful to all of you who are looking for a solution to this problem.

Why cant I add var in if statement

I'm trying to run a simple program to teach my friend to code:
var name = prompt("Whats your name");
if name = "Jason" {alert ("your name is Jason");
but for some reason it just wont let me ad the variable "name". What should I do?
I think you need
if (name === "Jason") { /*Do something */}
Rather than the single equals. Double/triple equals compares whereas single equals sets.

Msgbox if YES or NO

This should be super easy! The code merely consists of a message box with a Yes or No choice. Given that choice, a corresponding string is written into cell A1. I see no problem with it compared to google's script examples. What am I missing?
function msgbox() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var answer = Browser.msgBox("Confirm", "Does this work?", Browser.Buttons.YES_NO);
//if user clicks yes
if(answer === Browser.Buttons.YES) {
//then enter YES into cell A1
s.getRange("A1").setValue() === "YES";
} else {
//else enter NO into cell A1
s.getRange("A1").setValue() === "NO";
};
}
I have never used Google App Scripts, but based on my other programming experiences, I feel like
s.getRange("A1").setValue() === "YES";
might be the problem. Usually, the '===' operator is used to compare 2 values.
'aaa' === 'aaa' --> return true
In your case, don't you want to set a value?
s.getRange("A1").setValue("YES");
is what I would feel appropriate.
You are simply using setValue() the wrong way.
Refer to the documentation here.
It should simply be s.getRange("A1").setValue('YES')

Why aren't these two strings the same?

I'm trying to write some javascript and get some elements by using document.getElementById("ct100_ContentPlaceHolder1_search"); and for some reason it wouldn't find it. It would always return null.
After playing around thinking it was my use of double quotes or single quotes, I found the element's id in the document, and printed the id to a textbox. I copy/pasted the text to notepad and then decided to write this little bit of code
var id = e.target.id;
if (id == "ctl00_ContentPlaceHolder1_search") { <-- Copied/pasted from notepad. Returns true
var foo6 = document.getElementById("ctl00_ContentPlaceHolder1_search");
}
if (id == "ct100_ContentPlaceHolder1_search") { <-- Typed out. Returns false
var foo5 = document.getElementById("ct100_ContentPlaceHolder1_search");
}
The page is being built with ASP.NET if that matters at all. So what's going in? I haven't got a clue.
Here's a regexr I made to show the two strings aren't the same. The regular expression is the copied/pasted from notepad. It shows that the '1' is different, but what kind of '1' is that?
The first string has a lower-case L in ctl.
The second has the number 1 in ct1.

Categories

Resources