通过网络服务格式化电话号码

在我的网页中,我想格式化电话号码。例如,67291961

067/29.19.61

在我的页面 dashboad-homepage.component.html 中:

我有变量 welcomeMessage 允许显示以下消息:(这是屏幕截图)

{{welcomeMessage}} <a href="mailto:{{agent.MAIL}}">{{agent.MAIL}}</a>

通过网络服务格式化电话号码

为了能够格式化我的电话号码,我必须转到页面 dashboad-homepage.component.ts 然后格式化变量 agentPhone 但如何格式化 agentPhone

我知道问题在下面,但我不知道如何格式化?

prepareDataForTemplate(res){
if(res.RETURNCODE == 'OKK00'){
this.mifid = res.HOME.MIFID;
this.news = [];
this.securities = [];
this.agent = res.HOME.AGENT;
this.message = res.HOME.MESSAGE;
this.welcomeMessage = res.HOME.WELCOME;
this.i18n.agentName = this.agent.NAME;
this.i18n.agentMail = this.agent.MAIL;
this.i18n.agentPhone = this.agent.PHONE;
this.nOSTs = res.HOME.OSTNUMERO;
for(var i = 0; i < res.HOME.ARTICLE.length; i++){
var myvar = {
objet: res.HOME.ARTICLE[i].OBJET,cours: res.HOME.ARTICLE[i].COURS,source: res.HOME.ARTICLE[i].SOURCE,id: res.HOME.ARTICLE[i].NUMERO,date: res.HOME.ARTICLE[i].DATE[8]+res.HOME.ARTICLE[i].DATE[9]+"/"+res.HOME.ARTICLE[i].DATE[5]+res.HOME.ARTICLE[i].DATE[6],dateH: this.helpers.formatDateHeureAS400HeureHP(res.HOME.ARTICLE[i].HEURINTRO),svm: res.HOME.ARTICLE[i].SVM,ticker: res.HOME.ARTICLE[i].STOCK,DATEINTRO: this.helpers.formatDateHeureAS400DayMonth(res.HOME.ARTICLE[i].DATEINTRO,res.HOME.ARTICLE[i].HEURINTRO),HEURINTRO: this.helpers.formatDateHeureAS400HoursMinutes(res.HOME.ARTICLE[i].DATEINTRO,res.HOME.ARTICLE[i].HEURINTRO)
};

有关信息,这里是代码 dashboad-homepage.component.ts 的一个想法,抱歉有很多行:

import { Component,OnInit,NgZone } from '@angular/core';
import { MySharedService } from "src/app/shared/services/my-shared.service";
import { DataLayerService } from "src/app/shared/services/data-layer.service";
import { LocalStoreService } from "src/app/shared/services/local-store.service";
import { HelpersService } from "src/app/shared/services/helpers.service";
import { echartStyles } from 'src/app/shared/echart-styles';
import { Router } from '@angular/router';
import { DateddmmyyyyhiPipe } from 'src/app/shared/pipes/dateddmmyyyyhi.pipe';
import { TimehhmmPipe } from 'src/app/shared/pipes/timehhmm.pipe';
import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";
import am4themes_animated from "@amcharts/amcharts4/themes/animated";

am4core.useTheme(am4themes_animated);



@Component({
selector: 'app-dashboad-home',templateUrl: './dashboad-home.component.html',styleUrls: ['./dashboad-home.component.css'],providers: [ DateddmmyyyyhiPipe,TimehhmmPipe]
})
export class DashboadHomeComponent implements OnInit {

currentPortfolio: any;
sectionTitle: String;
pageTitle: String;
agent;
news: any;
markets: any;
securities: any = [];
variationPlace: any;
svmToTickers: any;

showCharts: false;
placeNames: any;

chartLineOption3: any;
lineChartReturn: any;

message;
welcomeMessage;
nOSTs;
nCGIs;
header_info;
mifid;
showHistoryCharts;
singleHistoryCharts;

i18n;
subscribedTo;

constructor(
private shrd: MySharedService,private api: DataLayerService,private helpers: HelpersService,private LS: LocalStoreService,private zone: NgZone,private router: Router,private dateddmmyyyyhi: DateddmmyyyyhiPipe,private timehhmm: TimehhmmPipe,) {

this.agent = {};
this.agent.MAIL = '';
this.i18n = {
lastErrordate: '',lastErrorHeure: '',lastConnexionDate: '',lastConnexionHeure: '',agentName: '',agentPhone: '',agentMail: ''
}
this.message = 0;
this.mifid = {};
this.markets = {};
this.header_info = {};
this.showHistoryCharts = [];
this.singleHistoryCharts = [];
this.subscribedTo = [];
this.nOSTs = [];
this.nCGIs = [];
this.variationPlace = [];
this.placeNames = [
{
exist: false,name: '',id: 0
},{
exist: false,];
}


private chart: am4charts.XYChart;


// AM Chart,ngAfterViewInit() {
this.zone.runOutsideAngular(() => {

});
}

ngOnDestroy() {
this.zone.runOutsideAngular(() => {
if (this.chart) {
this.chart.dispose();
}
});
}
// Amchart

ngOnInit() {

this.currentPortfolio = this.shrd.getData('currentPortfolio');
this.sectionTitle = "My Title";
this.pageTitle = "Welcome";
this.svmToTickers = {};

this.header_info = this.LS.getItem("LX_INFO_HEADER");
this.i18n.lastConnexionHeure = this.timehhmm.transform(this.header_info.LAHECO);
this.i18n.lastConnexionDate = this.dateddmmyyyyhi.transform(this.header_info.LADACO);
this.i18n.lastErrorHeure = this.timehhmm.transform(this.header_info.LAHEPWD);
this.i18n.lastErrordate = this.dateddmmyyyyhi.transform(this.header_info.LADAPWD);

this.lineChartReturn = {
...{},...{
tooltip: {
trigger: 'axis',position: function (pt) {
return [pt[0],'10%'];
}
},xAxis: {
type: 'category',// boundaryGap: false,//show: true,data: []
},yAxis: {
type: 'value',show: true
},series: [
{
name:'',type:'line',smooth:true,symbol: 'none',sampling: 'average',itemStyle: {
color: 'rgba(255,152,.6)',// 'rgb(255,70,131)'
},areaStyle: {
color: 'rgba(255,0.15)',origin: 'start'
},linestyle: {
// width: 1,color: 'rgba(255,},data: []
}
]
}
};

this.chartLineOption3 = {
...echartStyles.lineNoAxis,...{
series: [{
data: [],linestyle: {
color: 'rgba(102,51,153,.86)',width: 3,shadowColor: 'rgba(0,.2)',shadowOffsetX: -1,shadowOffsetY: 8,shadowBlur: 10
},label: { show: false,color: '#212121' },type: 'line',smooth: true,itemStyle: {
borderColor: 'rgba(69,86,172,0.86)'
}
}]
}
};

this.initiate();
}

designAmcharts(divID,instrumentTitle,amChartsData){
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end

// Create chart instance
var chart = am4core.create(divID,am4charts.XYChart);

chart.dateFormatter.dateFormat = "HH:MM ";
chart.numberFormatter.numberFormat = "#.#a €";
chart.numberFormatter.bigNumberPrefixes = [
{ "number": 1e+3,"suffix": "K" },{ "number": 1e+6,"suffix": "M" },{ "number": 1e+9,"suffix": "B" }
];

// Chart title
var title = chart.titles.create();
title.text = instrumentTitle;
title.fontSize = 20;
title.paddingBottom = 10;

// Add data
chart.data = amChartsData;
/*
chart.data = [{ "date": new Date(2020,6,1),"observed": 720000,"easing": 720000,"projection": 720000,"stricter": 720000
},{
......
}
];
*/

// Create axes
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
dateAxis.renderer.minGridDistance = 30;
dateAxis.renderer.labels.template.rotation = -45;
dateAxis.renderer.labels.template.horizontalCenter = "right";
dateAxis.renderer.labels.template.verticalCenter = "middle";

var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

valueAxis.renderer.labels.template.verticalCenter = "bottom";
valueAxis.renderer.labels.template.dx = -5;
valueAxis.renderer.labels.template.dy = 10;
valueAxis.renderer.maxLabelPosition = 0.95;

valueAxis.title.marginRight = 5;

// Create series
function createSeries(field,name,color,dashed) {
var series = chart.series.push(new am4charts.Lineseries());
series.dataFields.valueY = field;
series.dataFields.dateX = "date";
series.name = name;
series.tooltipText = "[bold]{name}[/]\n{dateX}: [b]{valueY}[/]";
series.strokeWidth = 2;
//series.smoothing = "monotoneX";
series.stroke = color;

if (dashed) {
series.strokeDasharray = "5 3";
}
return series;
}
createSeries("price","price",am4core.color("#A60027"),false);

chart.cursor = new am4charts.XYCursor();
/**/
}

getSubcriptionsList() {
this.api.getMarketsDataSubcriptionsList(this.currentPortfolio)
.subscribe((response: {}) => {
this.getUnansweredCGI();
// Save in the
this.prepareDataForMarketDataSubscriptions(response);
});
}

relaunch(){
this.initiate();
}

getUnansweredCGI() {
this.api.getUnansweredCGI(this.currentPortfolio,"O",0)
.subscribe((response: {}) => {
this.getHomePageContent();
this.prepareDataForUnansweredCGI(response);
});
}
prepareDataForUnansweredCGI(res){
if(res.RETURNCODE == 'OKK00'){
this.nCGIs = res.CGI;
this.LS.setItem("LX_num_CGIs",res.CGI.length);
}else {
// Service to report and manage errors (faire remonter au Backend)
}
}
getHistoryDataFormated2(data,dates){
let toReturn = this.lineChartReturn;
toReturn.xAxis.data = dates;
toReturn.series[0].data = data;

return toReturn;
}
getHistoryDataFormated(data){
let toReturn = this.chartLineOption3;
toReturn.series[0].data = data;
return toReturn;
}

getHomePageContent() {
this.api.getHomePageContent(this.currentPortfolio)
.subscribe((response: {}) => {
this.prepareDataForTemplate(response);
});
}


initiate(){
this.getallMarkets();

}

getH(i,svm){
this.api.getInstrumentHistoryEquities(svm,'1D')
.subscribe((response: {}) => {
this.prepareDataForHistory(response,i);
});
}

getHIndices(i,svm){
this.api.getInstrumentHistoryIndices(svm,i);
});
}

prepareDataForHistory(res,internalID){
for(var i = 0; i < this.securities.length; i++){
if(this.securities[i].internalID == internalID && res.HISTO.POINT.length > 0){
for(var j = 0; j < res.HISTO.POINT.length; j++){
this.securities[i].amChartsData.push({
"date": new Date(res.HISTO.POINT[j].DATE+" "+res.HISTO.POINT[j].TIME),"price": res.HISTO.POINT[j].PRICE
});
}
this.securities[i].historyExist = true;
}
}
for(var i = 0; i < this.securities.length; i++){
if(this.securities[i].internalID == internalID && this.singleHistoryCharts.indexOf(internalID) == -1){
if(this.securities[i].amChartsData.length > 0){
this.designAmcharts(("chartdiveq"+i),this.securities[i].name,this.securities[i].amChartsData);
this.singleHistoryCharts.push(internalID);
this.showHistoryCharts.push(i);
console.log(this.showHistoryCharts)
}
}
}
}

canShowHistoryCharts(i){
return this.showHistoryCharts.indexOf(i) > -1;
}

prepareDataForMarketDataSubscriptions(res){
if(res.RETURNCODE == 'OKK00'){
console.log(res)
for(var i = 0; i < res['ABO'].length; i++){
if(res['ABO'][i]['ABOCLIENT'] == 'Y'){
this.subscribedTo.push(res['ABO'][i]['PLAC']);
}
}
this.LS.setItem("LX_MARKET_DATA",this.subscribedTo);
}else {

}
}
prepareDataForTemplate(res){
if(res.RETURNCODE == 'OKK00'){
this.mifid = res.HOME.MIFID;
this.news = [];
this.securities = [];
this.agent = res.HOME.AGENT;
this.message = res.HOME.MESSAGE;
this.welcomeMessage = res.HOME.WELCOME;
this.i18n.agentName = this.agent.NAME;
this.i18n.agentMail = this.agent.MAIL;
this.i18n.agentPhone = this.agent.PHONE;
this.nOSTs = res.HOME.OSTNUMERO;
for(var i = 0; i < res.HOME.ARTICLE.length; i++){
var myvar = {
objet: res.HOME.ARTICLE[i].OBJET,res.HOME.ARTICLE[i].HEURINTRO)
};
this.news.push(myvar);
}
for(var i = 0; i < res.HOME.PREFERENCE.VALEUR.length; i++){
let curSec= res.HOME.PREFERENCE.VALEUR[i];
let timsec = i*10*45;
if( (curSec.SVM > 0 && curSec.TYP == 'A') || (curSec.TYP == 'I' && curSec.COD.length > 0) ){
this.securities.push({
type: curSec.TYP,name: curSec.LIB,svm: curSec.SVM,code: curSec.COD,internalID: curSec.SVM+'-'+curSec.COD,last: curSec.COURS.VALUE,variation: ((curSec.COURS.VALUE/curSec.COURS.CLOTURE-1)*100),historyExist: false,historyDataDates: [],historyData: [],history: {},history2: {},showLine: true,amChartsData: []
});
// if(!this.alreadyAskedHistoryFor(curSec)){
setTimeout(() => {
if(curSec.TYP == 'A' && curSec.SVM > 0){
this.getH(curSec.SVM+'-'+curSec.COD,curSec.SVM);
// this.singleHistoryCharts.push(curSec.SVM);
}else if(curSec.TYP == 'I' && curSec.COD.length > 0){
this.getHIndices(curSec.SVM+'-'+curSec.COD,curSec.COD);
// this.singleHistoryCharts.push(curSec.COD);
}
},timsec);
// }
} else {
this.securities.push({historyExist: false,showLine: false});
}
}


this.variationPlace = [res.HOME.VARIATIONPLACE1,res.HOME.VARIATIONPLACE2,res.HOME.VARIATIONPLACE3];
this.updatePlaceNames(res.HOME.PREFERENCE.PLAC1,res.HOME.PREFERENCE.PLAC2,res.HOME.PREFERENCE.PLAC3);


// Variation places
// Get the last history

}else {
// Service to report and manage errors (faire remonter au Backend)
}
}

alreadyAskedHistoryFor(curSec){
let res = false;
if(curSec.TYP == 'A' && curSec.SVM > 0){
res = this.singleHistoryCharts.indexOf(curSec.SVM) > -1;
}else if(curSec.TYP == 'I' && curSec.COD.length > 0){
res = this.singleHistoryCharts.indexOf(curSec.COD) > -1;
}
return res;
}


updatePlaceNames(pl1,pl2,pl3){
// console.log(pl1,pl3);
this.placeNames = [{
exist: (pl1 >= 1 ? true : false ),name: this.markets[pl1],id: pl1
},{
exist: (pl2 >= 1 ? true : false ),name: this.markets[pl2],id: pl2
},{
exist: (pl3 >= 1 ? true : false ),name: this.markets[pl3],id: pl3
}];
// console.log(this.placeNames,this.variationPlace);

}

getallMarkets(){
this.api.getParametersAllMarkets()
.subscribe((response) => {
this.getSubcriptionsList();
if(response['RETURNCODE'] == 'OKK00'){
for(var i = 0; i < response['TEXTE']['LISTE'].length; i++){
this.markets[parseInt(response['TEXTE']['LISTE'][i].CODE)] = response['TEXTE']['LISTE'][i].COURT;
}
}else {
// manage this error
}
});
}

getandCacheSignaletique(svm){
this.getTicker(svm);
}

getTicker(svm){
this.api.getInstrumentInfo(svm)
.subscribe((response) => {
if(response['RETURNCODE'] == 'OKK00'){
this.svmToTickers[svm] = response['ADVTITRE'].BASIQUETITRE.STOCK;
// console.log(this.svmToTickers);
/*
TODO this.cacheSignaletique(response);
*/
}else {
// manage this error
}
});
}

getTickerFromSVM(svm){
// TODO Check if it's cached.
// console.log(this.svmToTickers);
return this.svmToTickers[svm] ? this.svmToTickers[svm] : "";
}

goToDetails(n){
let detailsId = n.type == 'I' ? n.code : n.svm
// TODO if it's index go to Indices
// this.router.navigateByUrl("/markets/details/"+detailsId);
this.goToDeatilsSVM(detailsId);
}

goToDetailsFromPerf(l){
this.goToDeatilsSVM(l.SVM);
}

goToDeatilsSVM(svm){
this.router.navigateByUrl("/markets/details/"+svm);
}

goToOSTNews(l){
// console.log(l)
this.router.navigateByUrl("/markets/details/"+l.svm+"/news/"+l.id);
}

goToMails(){
this.router.navigateByUrl("/dashboard/mails");
}

goToOSTs(){
this.router.navigateByUrl("/portfolio/corporateactions");
}

goToCGIs(){
this.router.navigateByUrl("/portfolio/recommandations");
}


showInformationsOnPTF(){
return (this.nOSTs.length > 0 || this.nCGIs.length > 0 ); // OR another thing messages length
}

showLastLogin(){
return this.header_info.LADACO > 0;
}

showLastError(){
return this.header_info.LADAPWD > 0;
}
}

如果你有什么想法,我很感兴趣。

hygzp 回答:通过网络服务格式化电话号码

您可以使用正则表达式来执行此操作,这是使用正则表达式的简单解决方案:

const phone = '9876543210'; //change it's value 
let result = '';

switch(phone.length) {

    case 8: 
             result=  phone.replace(/(\d{2})(\d{2})(\d{2})(\d{2})/,"0$1/$2.$3.$4");  
               break;
    case 9:  
            result = phone.replace(/(\d{3})(\d{2})(\d{2})(\d{2})/,"0$1/$2.$3.$4");
             break;
     case 10:  
            result = phone.replace(/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/,"0$1/$2.$3.$4.$5");
             break;  
}
console.log(result);

本文链接:https://www.f2er.com/1968.html

大家都在问