Home > Blockchain >  How can I get value from input, replace certain characters from the value, and not get an undefined
How can I get value from input, replace certain characters from the value, and not get an undefined

Time:08-24

I am trying to get the value of an input, replace certain characters from it, and store the new value in a variable. However, with my current code, I get an "undefined" value at the end of it all.

This is my code right now. It is a bit of a mess because i've been trying different methods since last night to no avail.

var diceType = document.getElementById('set');
const newdiceType = (diceType) => {
        return diceType.toString().replace(/{}a!/g, "");
        };
        diceType = newdiceType;
        alert(diceType.value);

Previously to that, I had something like this:

var diceType = document.getElementById('set');
var newdiceType = "";
newdiceType = parseFloat(diceType.toString().replace(/{}a!/g, ''));
alert(newdiceType.value);

What I really want to do is the following in javascript (any assistance with this would be greatly appreciate it):

  1. Get the value from the input.
  2. Replace all characters from that value that are not numbers, the letter "d", and the plus sign " ." e.g., If the input value is "3d6 2 {a}", or "4d10 {b} !!!" I will get 3d6 2 or 4d10.
  3. Store the new value inside variable "newdiceType" Display the value of "newdiceType" in an alert and not show as "undefined." E.g., if modified results from step 2 is "3d6 2" then the alert will display "3d6 2."

CodePudding user response:

Something like this is what you need:

const replaceDiceType = (diceType) => {
    const rem = diceType.toString().replaceAll(/\{.*?\}|\s|!/g,"");
  return rem
}
const handleInputValue = () => {
    const diceTypeInput = document.getElementById('set').value;
  const newDiceType = replaceDiceType(diceTypeInput);
  alert(newDiceType);
}
<input type="text" id="set" placeholder="Input here"/>
<button type="button" onClick="handleInputValue()">Enter Value</button>

  • First to get the value of an input by calling it by a selector you must use its .value property Read here.

  • Then the regex i'm using will search the whole string for the cases in which { } ! exists and that there is also something inside the brackets..

  • Finally I have added a button so that it does not run at startup, and you could use an onChange of the input to show the changes every time a change is detected in the input Read here.

CodePudding user response:

try this out :

function replaceDiceType(diceType) {
    return diceType.replace(/[^a-zA-Z0-9 ]/g, "");
}

var diceType = document.getElementById('set').value;
alert(replaceDiceType(diceType));
  • ^ negates what follows
  • a-zA-Z matches upper and lower case letters
  • \d matches digits
  • \ matches
  • Related