Ada
Ada

Reputation: 569

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

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>

Upvotes: 0

Views: 165

Answers (2)

Anis R.
Anis R.

Reputation: 6912

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>

Upvotes: 0

Sonth
Sonth

Reputation: 11

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;
}

Upvotes: 1

Related Questions