-3

I wrote this code:

if (!prefix.match(/^[+][0-9]+\s[0-9]+$/)){    
    Xrm.Page.getControl("phone").setNotification("Please write a valid phon number");
}    
else 
    (prefix.match(/^[+][0-9]+$/)) { ??? }

In if, I define that in the field phone number, the number should be written like this : +49 15792423

Now I want to say, if somebody write the phone number like this: +4915792423, it should put automatically a space between 9 and 1.

So can one of you please write the new code?

Best Regards

Jal
  • 1
  • 1
  • 1
    Possible duplicate of [JavaScript: How can I insert a string at a specific index](https://stackoverflow.com/questions/4313841/javascript-how-can-i-insert-a-string-at-a-specific-index) – barbsan Oct 22 '18 at 11:40

1 Answers1

0

You don't even need to use regex, simple check for space at the 3rd index would be enough

const tel1 = "+49 15792423";
const tel2 = "+4915792423";

function fixNumber(phoneNumber){
    if (phoneNumber[3]!=" ") return phoneNumber.substring(0, 3)+" " + phoneNumber.substring(3);
    else return phoneNumber;
}

console.log(fixNumber(tel1)); //returns  +49 15792423
console.log(fixNumber(tel2)); //returns  +49 15792423

Use with regex as requested checks for spacebar after first 2 digits found

function fixNumber(phoneNumber){
    if (phoneNumber.match(/\+\d{2} /)) return phoneNumber;
    else return phoneNumber.substring(0, 3)+" " + phoneNumber.substring(3);
}

console.log(fixNumberByRegex(tel1)); //returns  +49 15792423
console.log(fixNumberByRegex(tel2)); //returns  +49 15792423
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
  • Thanks, I will try it. Could you please write this once with regex? because the telephone number is not always +49 15792423. It can be any telephone number. Thank you again Best regards – Jal Oct 22 '18 at 12:39
  • well the function i wrote, does not care about the first 3 symbols and ensures the spacebar on the next one (so it does apply also to other numbers) – Krzysztof Krzeszewski Oct 22 '18 at 12:50