Arunya
Arunya

Reputation: 291

how to remove + symbol from phone number using reactjs

My objective is to remove + symbol from the phone number and store the respective phone number in another variable.

class App extends Component {
this.state={
phone: '',
renumber: ''
}

componentDidMount() {
  axios.get('/api/phone')
  .then(response => {
    console.log(response.data);
this.setState({phone: response.data}) //I want to remove + symbol from variable `phone - +78945612301` and then save it to `renumber variable - 78945612301`
  })
  .catch(error => {
    console.log(error);
  });
}

withoutSign = () => {
let num = this.state.phone.replace('+', ' ') 
this.setState({renumber: num})
}

render(){
return(
<div>{this.state.phone} </div>
<div>{this.state.renumber} </div>
);
}
}

Can anyone help me in getting phone number without + symbol

Upvotes: 0

Views: 1247

Answers (2)

Anku Singh
Anku Singh

Reputation: 954

Try this it will work and hope it will solve your problem

    withoutSign = () => {
       let num = this.state.phone.replace(/\+/g,"");
       this.setState({renumber: num})
    }

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 203348

Issues

  • Initial state outside constructor is just a class instance, i.e. state vs this.state
  • Convert withoutSign to consume a string and simply return the converted string value for inline use
  • Setting state is this.setState

Solution

class App extends Component {
  state = {
    phone: "",
    renumber: ""
  };

  componentDidMount() {
    axios
      .get("/api/phone")
      .then(response => {
        console.log(response.data);
        this.setState({
          phone: response.data,
          renumber: this.withoutSign(response.data),
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

  withoutSign = phone => phone.replace("+", " ");

  render() {
    return (
      <div>
        <div>{this.state.phone}</div>
        <div>{this.state.renumber}</div>
      </div>
    );
  }
}

Edit telephone number char replace

Upvotes: 2

Related Questions