How to display number to **** ****

Viewed 105

I want convert number to * and add space after every 4 digits. ex: 12345678 -> 1234 5678 -> **** **** Now i just convert number to * but can't add space . ( when convert number to * , add space function not work ) Please help me!

import React, { Component } from 'react';
import { Text, TextInput, View } from 'react-native';

export default class PizzaTranslator extends Component {
  constructor(props) {
    super(props);
    this.state = {text: ''};
  }

  render() {
    return (
      <View style={{padding: 10}}>
        <TextInput
          style={{height: 40}}
          placeholder="Type here to translate!"
          onChangeText={(text) => this.setState({text})}
          value={this.state.text}
        />
        <Text style={{padding: 10, fontSize: 42}}>
{this.state.text.replace(/(\(-?\d+(?:\.\d*){4})/g,'$1').replace(/(^\s+|\s+$)/,'') .slice(20).padStart(this.state.text.length, '*')}
        </Text>
      </View>
    );
  }
}

i expect input : 123456789123 output: **** **** ****

3 Answers

One line Answer:

"123456781234".replace(/[0-9]/g, "*").match(/.{1,4}/g).join(" ");

Try this for grouping

this.state.text.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();

Edit: how to split '********' in javascript

var str = "************";
var chuncks = str.match(/.{1,4}/g);
var new_value = chuncks.join(" "); //returns **** **** ****

Following will be the complete answer after combining the above two:

var starString = "123456781234".replace(/[0-9]/g, "*");
var chuncks = starString.match(/.{1,4}/g);
var new_value = chuncks.join(" "); //returns **** **** ****

You could just go oldskool and use a loop. :-)

const num = 123456789123456789;
const preStr = num.toString();
let postStr = "";

for(var i = 0; i < preStr.length; i++){
    postStr += '*';
    i % 4 === 3 && (postStr += ' ');
}
console.log(postStr)
// output: **** **** **** **** **

As a function:

const format = input => {
    let output = "";
    for(var i = 0; i < preStr.length; i++){
        output += '*';
        i % 4 === 3 && (output += ' ');
    }
    return output;
}
console.log(format("123456789123456789"));

// output: **** **** **** **** **
Related