What are some ways to effectively utilize a mask for values retrieved from a database?

Hello, I am working on fetching data from my database and want to display it in a specific format within my view. Currently, my code is simple with a table displaying the data from the database. However, I need to format a phone number with a mask like this: (12) 94832-3823. I have tried various approaches but so far, no success. Can anyone provide me with some guidance or a hint?

Here is a snippet of my table code:

<table class="table table-bordered" id="example10" width="100%" cellspacing="0">
   <thead>
      <tr>
         <th>{{ __('messages.serial no')}}</th>
         <th>{{ __('messages.Delivery_Boy')}}</th>
         <th>{{ __('messages.Delivery_Boy_Image')}}</th>
         <th>{{ __('messages.Delivery_Boy_Phone')}}</th>
         <th>{{ __('messages.Status')}}</th>
         <th>{{ __('messages.action')}}</th>
      </tr>
      </tfoot>
   <tbody>
      @if(count($delivery_boy)>0)
      @php $i=1; @endphp
      @foreach($delivery_boy as $delivery_boys)
      <tr>
         <td>{{$i}}</td>
         <td>{{$delivery_boys->delivery_boy_name}}</td>
         <td align="center"><img src="{{url($delivery_boys->delivery_boy_image)}}" style="width: 21px;"></td>
         <td>{{$delivery_boys->delivery_boy_phone}}</td>
         <td>
            @if($delivery_boys->is_confirmed==0)
            <a href="{{route('confirm.delivery.status',[$delivery_boys->delivery_boy_id,'1'])}}" class="btn btn-info" style="color: #fff;">Yes</a>
            <a href="{{route('confirm.delivery.status',[$delivery_boys->delivery_boy_id,'2'])}}" class="btn btn-danger" style="color: #fff;">No</a>
            @elseif($delivery_boys->is_confirmed == 1)
            <span style="color:green;">Aprovado</span>
            @else
            <span style="color:red;">Reprovado</span>
            @endif
         </td>
         <td>
            <a href="{{route('edit-delivery_boy',$delivery_boys->delivery_boy_id)}}" style="width: 28px; padding-left: 6px;" class="btn btn-info"  style="width: 10px;padding-left: 9px;" style="color: #fff;"><i class="fa fa-edit" style="width: 10px;"></i></a>
            <button type="button" style="width: 28px; padding-left: 6px;" class="btn btn-danger" data-toggle="modal" data-target="#exampleModal{{$delivery_boys->delivery_boy_id}}"><i class="fa fa-trash"></i></button>
         </td>
      </tr>
      @php $i++; @endphp
      @endforeach
      @else
      <tr>
         <td>No data found</td>
      </tr>
      @endif
   </tbody>
</table>

Current display can be seen at this link: https://i.sstatic.net/2LOpY.png

Thank you for your time!

Answer №1

To simplify the process, you can delete the php echo phone and insert fixed text instead. For example: <td>xxx-xxx-xxx</td>.

UPDATE

You have javascript tagged in your question. Here is a Javascript version: The crucial part is the regex pattern. Use this pattern: /(\d{2})(\d{5})(\d+)/

Javascript Example:

function formatPhoneNumber(phoneNumberString) {
  
  var cleaned = ('' + phoneNumberString).replace(/\D/g, '');
  
  var match = cleaned.match(/(\d{2})(\d{5})(\d+)/);  
  if (match) {
    return '(' + match[1] + ') ' + match[2] + '-' + match[3];
  }
  return null;
}

p = "+5511920140349"

console.log( formatPhoneNumber(p) )

Appendix

Replace the line with the phone number from

<td>{{$delivery_boys->delivery_boy_phone}}</td>
to
<td class="phonenumbers">{{$delivery_boys->delivery_boy_phone}}</td>
. Now, you can select and modify the lines using js. Like this:

const nums = document.querySelectorAll('.phonenumber');
console.log(nums)

nums.forEach(td => {
  const p = td.innerHTML;
  td.innerHTML = formatPhoneNumber(p)  
})


function formatPhoneNumber(phoneNumberString) {  
  var cleaned = ('' + phoneNumberString).replace(/\D/g, '');  
  var match = cleaned.match(/(\d{2})(\d{5})(\d+)/);  
  if (match) {
    return '+(' + match[1] + ') ' + match[2] + '-' + match[3];
  }
  return null;
}
<table border="1px">
  <tr>
    <td>abc</td>
    <td class="phonenumber">123456789</td>
  </tr>
  <tr>
    <td>abc</td>
    <td class="phonenumber">123456789</td>
  </tr>
  <tr>
    <td>abc</td>
    <td class="phonenumber">123456789</td>
  </tr>  
</table>

Answer №2

One clever trick you can use is using a regular expression to replace all the numbers with a letter 'X'.

To mask a phone number, you can simply apply this line of code:

preg_replace('/\d/', 'X', '+5511920140349');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending data through ajax to PHP on separate pages is a common practice

Here is where I choose my preferred option Company Name<br /> <select id="company" name="selected"> <option value="">Option A</option> <option value="">Option B</option> </select> When I click this, a mo ...

Is it possible to automatically submit a form at regular intervals without reloading the page and simultaneously insert the submitted data into

I am attempting to automatically submit a form every x number of seconds without refreshing the page and then insert the input data into a MYSQL database. The problem I'm facing is that while I can successfully insert the form's input value into ...

Using Selenium to interact with a Modal Dialog window

When trying to navigate to a page in IE9 using Selenium, a certificate error message appears on the page. By using AutoIT, I am able to click within the browser, TAB twice, and hit enter without any issues. However, after this step, an error for a "Modal d ...

Prevent double clicking on select tags that are automatically generated

Hey there, I have successfully designed a select field on my HTML page that closely resembles the Django admin manytomany field. You can check it out HERE. However, I am now facing an issue with disabling the double click function on this field. I've ...

Updating the icon of an action column dynamically in Ext JS4

Using the getClass function to display icons in the action column: { xtype: 'actioncolumn', id:'actionColumnGridUsers', width: 30, hideable: false, items: ['->', { getClass: function (v, meta, rec) { ...

Monitoring Logfile in Ruby On Rails 3.1

Within my Ruby on Rails application, I have a set of scripts that need to be executed. In order to ensure they are working properly, the application must display and track the content of logfiles generated by these scripts. To provide more context: I util ...

Leveraging node.js to power mobile applications along with an administration panel built using angular

Our current setup involves a mobile app that communicates with some APIs (no backend yet). I'm considering using node.js as a service for these APIs, even though I've never used it before being primarily a .net developer. For the administrative ...

Button-controlled automated presentation

I have devised a method to create an automatic slideshow using JavaScript. However, I am looking to incorporate manual control buttons as well. After adding manual control code, the slideshow seems to be malfunctioning. The provided code below is used for ...

Transferring JSON data from JavaScript to ASP.NET

In my web app, the backend is built in ASP.net. The ajax call I'm using is a standard get request. $.ajax({ url: 'myurl/updatejson', contentType: "application/json; charset=utf-8", data: data, success: function (data) { ...

Display a progress bar on the index page of the grid view

Seeking assistance in displaying a progress bar on the grid view page index. Currently, I have successfully implemented a progress bar on button click and would like to replicate this functionality when the user switches from 1 to 2. Here is the modal pop- ...

Is utilizing R dygraphs for fractional timestamps possible?

Is there a workaround that allows for using the dygraphs package in R Shiny with fractional timepoints? While I know this package is primarily designed for time-series data, I believe it could also be valuable for creating survival plots. For instance, co ...

Jquery modal dialog experiencing issues with controls not working properly

In my ASP.net web app, I am utilizing the jQuery dialog. Inside this dialog, there is a user control with some links. However, when the dialog is set to modal mode, the links become unselectable. I attempted the solution mentioned in this post, but unfort ...

The mystery of the missing body in a Node.js post request

I have developed an API in Node.js and I am facing an issue with the POST method where the body is coming as undefined. How can I extract the value passed using fetch? Node.js Code------------------------------------------ const express=require('expr ...

Highchart mortgage calculator for accurate financial planning

I am looking to create a dynamic high chart similar to the one on bankrate.com, showcasing principal, balance, and interest over various years. Despite my efforts, I have been struggling to organize the data by year as demonstrated in the example above: ...

Using PHP to track the number of clicks on a specific div element

Although I am not well-versed in javascript, I have incorporated it into my website to enhance its appearance. One of the features I've added is a popup that appears when a user clicks on a specific div element to display additional information. In ad ...

What is the method used for defining an element within an array in JavaScript?

As I am new to JavaScript, I find myself trying to organize callbacks within an array. An example of what I have been working on: items = [ "test" = async message => { let userCoins = editCurrency('fetch', message.guild. ...

Adaptive grids in Bootstrap

I've been using bootstrap and I'm trying to get the items to align next to each other, but using the bootstrap columns doesn't seem to be working for me. I may be coding it incorrectly. <link rel="stylesheet" href="https://cdn.jsdelivr ...

Adjusting the size of SVG rectangle shapes within a group container

I'm struggling to resize an SVG in my website. It is located within the header of the site, and previously I was resizing a regular image like this: $("#block_175 img").height($("#header").height() / 2); Now that I switched to using an SVG, I have b ...

Creating Dynamic Where Statements using Sequelize and Multiple OR Conditions

The required MySQL query: SELECT * FROM myTable WHERE ( JSON_CONTAINS(access,'"a"','$.owner') OR JSON_CONTAINS(access,'"b"','$.owner') ) AND ( JSON_CONTAINS(access,'"c"','$.mode ...

Bootstrap 4 tooltip/popover with automatic fallback placement (utilizing two possible placement options)

In the past, Bootstrap 3 offered functionality to handle data-placement="left auto", which would display the tip on the left if there was sufficient space, or calculate an automatic placement if not. However, Bootstrap 4 does not support the use of two pl ...