How can I remove spaces, punctuation and symbol from my text - javascript

I am building an app whereby I have to make some conversions to an input string. I need to remove whitespaces, punctuation and make everything down-cased. I do not get any output when I try to test it.
Further, I need to ensure that more than one word is entered and at Least 60 characters in the input box.
const text = document.querySelector('#normalized_text');
const string = document.querySelector('#message');
function encodeMessage() {
let newMessage = string.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
console.log(newMessage);
text.innerHTML = newMessage;
return newMessage;
}
<form>
<input type="text" placeholder="Type your secret message" id="message">
</form>
<button type="submit" class="button" onclick="encodeMessage()">Encode message</button>
<div class="box">
<h3>Normalised Text</h3>
<p id="normalized_text"></p>
</div>

Currently, you're not replacing the value of the object 'string' but rather just the object. If you check your developer console, you will find an error message. I recommend using the developer console (by going to Inspect Element) as much as possible when creating a webpage because it can show the errors in your script.
You should change your JavaScript code to the following:
const text = document.querySelector('#normalized_text');
const string = document.querySelector('#message');
function encodeMessage() {
let newMessage = string.value.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
text.innerHTML = newMessage;
return newMessage;
}

A few issues here:
1- As pointed out by #epascarello, your button is of type submit, which by default refreshes the page. We do not want that in the case, so simply make your button to be of the type button.
2- You are trying to manipulate the object string, not its value! try working with string.value instead.
Regarding the word count checking, you can split the string by the space character and check the resulting array's length.
const text = document.querySelector('#normalized_text');
const str = document.querySelector('#message');
function encodeMessage() {
var message = str.value;
if(getWordCount(message) < 2 || message.length < 60) {
console.log("Invalid message.");
return null;
}
let newMessage = str.value.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
console.log(newMessage);
text.innerHTML = newMessage;
return newMessage;
}
//gets word count of a string
function getWordCount(s) {
return s.split(" ").length;
}
<form>
<input type="text" placeholder="Type your secret message" id="message">
</form>
<button type="button" class="button" onclick="encodeMessage()">Encode message</button>
<div class="box">
<h3>Normalised Text</h3>
<p id="normalized_text"></p>
</div>

Related

Text input command aguments

How would I make commands for an input tag. For example, when you type !echo 'test' in an text input it would edit the content of a p tag
I tried this
<input type="text id="input" onchange="update()"/>
<p id="output"></p>
function update(){
var x = document.getElementById("input").value;
if(x == "!echo ", args){
document.getElementById("output").innerHTML = x;
}
}
If I understand the question correctly, you want to show the text that appears after the command "!echo". You're very close to getting it done. I've used the startWith method on the string of x to ensure the '!echo' command is at the beginning of the input. If that's true then we strip off the command using the replace method. I hope that's what you're looking for.
function update(){
var x = document.getElementById("input").value;
if (x.startsWith("!echo ")) {
document.getElementById("output").innerHTML = x.replace('!echo ', '');
}
}
<input type="text" id="input" onchange="update()"/>
<p id="output"></p>
Your question is unclear AMO.
Here's the result if you type !echo 'test' in your input tag.
If that's not the result your expect please update your question.
Feel free to add more details if it's not the goal you want.
I don't understand exactly what You want to do...
Have a nice day.
<input type="text" id="input" onKeyUp="update('\'test\'')">
<p id="output"></p>
function update(args){
var x = document.getElementById("input").value;
if(x == "!echo "+ args){
document.getElementById("output").innerHTML = x;
}else{
document.getElementById("output").innerHTML ="";
}
}

I'm using pure JavaScript but I continue to get errors that end with "is not a function". How do make it so I can detect words and reply accordingly?

I want to detect a specific word or multiple words within the user's entered text and reply accordingly. I plan to add more words to detect but for now I've been using this.
My result is finalKey.contains is not a function.
<html>
<div>
<p1 id="iOut">🧰</p1>
</div>
<div>
<input id="uIn" value=""></input>
</div>
<button onclick="regis()">SUBMIT</button>
<script>
var key = document.getElementById("uIn").value;
var finalKey = key.toUpperCase();
function regis() {
if (finalKey.contains("Hi" || "H")) {
document.getElementById("iOut").innerHTML = "HEY";
} else if (finalKey.contains("Bye" || "Goodbye")) {
document.getElementById("iOut").innerHTML = "Okay";
} else {
document.getElementById("iOut").innerHTML = "🧰 Try again";
}
}
</script>
</html>
There is no such thing as contains. It is .includes or indexOf != -1
Your gathering of values needs to be inside the function too
Also you cannot test two values in one statement unless you turn it around and use an array:
["Hi","H"].indexOf(finalKey) !=-1
or
["HI","H"].filter(text => finalKey.startsWith(text)).length > 0
if you want finalkey to start with either - use .includes if you want to test the complete input
Lastly you uppercased the text so compare uppercase text
function regis() {
var key = document.getElementById("uIn").value;
var finalKey = key.toUpperCase();
if (["HI","H"].filter(text => finalKey.includes(text)).length > 0) {
document.getElementById("iOut").innerHTML = "HEY";
} else
if (["BYE","GOODBYE"].filter(text => finalKey.includes(text)).length > 0) {
document.getElementById("iOut").innerHTML = "Okay";
} else // GOOD has to be AFTER GOODBYE to not catch it
if (["GOOD","GREAT"].filter(text => finalKey.includes(text)).length > 0) {
document.getElementById("iOut").innerHTML = "That's Good";
} else {
document.getElementById("iOut").innerHTML = "🧰 Try again";
}
}
<div>
<p1 id="iOut">🧰</p1>
</div>
<div>
<input id="uIn" value="" />
</div>
<button type="button" onclick="regis()">SUBMIT</button>
Using regular expression and word boundaries
Note I wrapped in a form, now you can just hit enter too
const wordList = [
{ list: ["HI", "H"], answer: "HEY" },
{ list: ["BYE", "GOODBYE"], answer: "Okay" },
{ list: ["GOOD", "GREAT"], answer: "That's good" }
];
const defaultText = "🧰 Try again";
document.getElementById("inputForm").addEventListener("submit", e => {
e.preventDefault()
const input = document.getElementById("uIn").value.trim().toUpperCase();
let result = wordList
.filter(({ list, answer }) => list
.filter(word => new RegExp("\\b" + word + "\\b").test(input))
.length > 0);
console.log(result)
document.getElementById("iOut").innerHTML = result.length > 0 ? result[0].answer : defaultText;
})
<div>
<p1 id="iOut">🧰</p1>
</div>
<form id="inputForm">
<div>
<input id="uIn" value="" />
</div>
<button>SUBMIT</button>
</form>
You will want to use .includes() and not .contains().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
I'd recommend getting comfortable with Chrome's Developer Tools. For example, pull up a browser and enter "xyz". You will see various methods available, and contains() is not on the list.
Also, as #mplungjan pointed out, there are other problems here.
"Hi" || "H" evaluates to "Hi". So "HI" is entirely ignored here.
You could write finalKey.includes("Hi") || finalKey.includes("H")) instead, but this would get cumbersome as you add other conditions.
A better approach would be to use functional programming along these lines:
const wordsToTest = ['FOO', 'BAR'];
if (wordsToTest.find(word => finalKey.includes(word))) {
I was made aware that i made a fundemental mistake in my previous answer, so i came up with another solution. With this approach you will not have to make multiple if/else statements, however simply add new object to the array, i hope it is pretty self explanatory when looking at it :)
<html>
<div>
<p1 id="iOut">🧰</p1>
</div>
<div>
<input id="uIn" value=""></input>
</div>
<button onclick="regis()">SUBMIT</button>
<script>
function regis() {
let key = document.getElementById("uIn").value;
let finalKey = key.toUpperCase();
let match = false;
// Words to test for
autoComplete = [
{ // Hey
response: "hey",
input: [
'HI',
'H',
]
},
{ // Bye
response: "Bye",
input: [
'BYE',
'GOODBYE',
]
}
]
for (potentialMatch of autoComplete){
for (input of potentialMatch.input){
if (input === finalKey){
document.getElementById("iOut").innerHTML = potentialMatch.response;
match = true;
}
}
}
if (match === false)
document.getElementById("iOut").innerHTML = "🧰 Try again";
}
</script>
</html>

How to check and return a message if no value entered

I'm still learning and am trying to simply take a number from an input, add 7 to it, and then display it on the webpage. It all works fine, but what I don't like is if you hit "submit" without entering a number, the HTML field shows "NaN" vs. a custom message, which is what I'd like to do.
Here's the code I have so far. What am I missing to capture that nothing was entered and return a different message?
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
if (isNaN(number)){
document.getElementById("add").innerHTML ="Please enter a value";
}
else {
let original = parseInt(number,10);
num = addition + original;
document.getElementById("add").innerHTML = num;
}
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add"></p>
</div>
That is because an empty string actually returns true when passed to isNaN(), i.e. isNaN('') returns true.
To do that, you can simply move the check to the final step, a.k.a. evaluate the num variable instead:
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
let original = parseInt(number, 10);
let num = addition + original;
if (isNaN(num)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>
Alternatively, you can also simply parse the input element's value directly: it will inform you if it is not a number right away:
function add7() {
let number = parseInt(document.getElementById('num').value, 10);
if (isNaN(number)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
let addition = 7;
let num = addition + number;
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>

Javascript - text input to icon

I am trying to create a simple web application. Like in Facebook chat when I enter "(Y)" it turns into the thumbs up icon. Similarly I am trying to do something like that with the following code. But it is not working for me. I am not expert with JavaScript. I need some help that what's wrong with the code?
And I made the code in a way that if i enter "y" it will return LIKE. I want to know how to show an icon after "y" input.
<html>
<head>
<title>Emogic</title>
</head>
<body>
<input type="text" id="input">
<input onclick="appear()" type="submit">
<p id="output"></p>
<script>
function appear(){
var value = document.getElementByid("input").value
var result = document.getElementById("output").innerHTML
if(value == "y"){
result = "LIKE"
}
else if(value == ""){
alert("You must enter a valid character.");
}
else{
alert("Character not recognised.");
}
}
</script>
</body>
</html>
There are a few issues/typo in your code :
it's document.getElementById(), with a capital I in Id.
result will be a string, containing the innerHTML of your element, but not a pointer to this innerHTML : when you then set result to an other value, it won't change the element's innerHTML as you expected. So you need to create a pointer to the element, and then set its innerHTML from the pointer.
The quick fix of your code would then be :
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
if (value == "y") {
output.innerHTML = "LIKE";
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="y">
<input onclick="appear()" type="submit">
<p id="output"></p>
But you'll find out that your user will have to enter exactly "y" and only "y" for it to work.
I think you should use instead String.replace() method with a regular expression to get all occurences of a pattern, i.e, for "(Y)" it could be
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
// The Regular Expression we're after
var reg = /\(Y\)/g;
// your replacement string
var replacement = 'LIKE';
// if we found one or more times the pattern
if (value.match(reg).length > 0) {
output.innerHTML = value.replace(reg, replacement);
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="I (Y) it (Y) that">
<input onclick="appear()" type="submit">
<p id="output"></p>

Having trouble with input and output in Javascript

I have recently started doing my own project with javascript and I ran into a roadblock. I'm doing a reverse string project where the user inputs a string and the output reverses it. Now my problem is that I can't get the reverse string to show up in the output area.
The Javascript part:
<script>
function pass() {
var input = document.getElementById('inputfield');
var output = document.getElementById('results');
var string = input.value;
var reverse = function (string) {
return string.split('').reverse().join('');
};
output.innerHTML = reverse;
}
</script>
The HTML:
<div id="reverse">
<h1>Type Below:</h1>
<form name="form">
<input type="text" name="inputfield" id="inputfield">
<button onClick="pass();">Submit</button></br>
<input type="text" name="out" placeholder="results" id="results">
</form>
</div>
You need to call the function.
output.value = reverse(input.value);
Luis,
When creating one function that receive an parameter, never forget to send this parameter.
In this case:
output.innerHTML = reverse(yourparameter);
Regards.
you will get reversed string like this:
output.innerHTML = reverse(string);
because
var reverse = function (string) {
return string.split('').reverse().join('');
};
is just a function declaration, the string is only a parameter of the function, but not equal to
var string = input.value;

Categories