Javascript 获取空格前和空格后的符号(JS)

Javascript 获取空格前和空格后的符号(JS),javascript,angular,typescript,Javascript,Angular,Typescript,我有一个有电话号码的角分量 例如+36 42534534 我需要在空格前输入密码,在空格前输入电话号码 我是这样做的 set phoneNumberResult(value: string) { if (this.phoneNumberResult !== value) { this.phoneCode = value.substr(0, 3); this.phoneNumber = value.substr(5, value.length - 5);

我有一个有电话号码的角分量

例如
+36 42534534

我需要在空格前输入密码,在空格前输入电话号码

我是这样做的

set phoneNumberResult(value: string) {
    if (this.phoneNumberResult !== value) {
        this.phoneCode = value.substr(0, 3);
        this.phoneNumber = value.substr(5, value.length - 5);
        this.changed.forEach(f => f(value));
    }
}
但电话号码可以是3、4或5个符号。 因此,我需要获取空格前的所有符号和空格后的所有符号,以获取
phoneCode
phoneNumber

如何才能正确执行此操作?

尝试使用空格

let value=`+36 42534534`
设valueSplit=value.split(“”);
让phoneCode=valueSplit[0]
让phoneNumber=valueSplit[1]
console.log(电话码)
console.log(电话号码)
尝试使用空格

let value=`+36 42534534`
设valueSplit=value.split(“”);
让phoneCode=valueSplit[0]
让phoneNumber=valueSplit[1]
console.log(电话码)

console.log(phoneNumber)
如果字符串输入格式始终相同,则只需使用
split
(),这意味着它的前缀始终由数字分隔,并带有一个空格

set phoneNumberResult(value: string) {
    if (this.phoneNumberResult !== value) {
        let [phoneCode, phoneNumber] = value.split(' ');
        this.phoneCode = phoneCode;
        this.phoneNumber = phoneNumber;
        this.changed.forEach(f => f(value));
    }
}
split
在您的例子中,将返回一个数组,其中第一个元素将是被拆分字符串的左侧,第二个元素将是被拆分字符串的右侧


要使用的小提琴示例:

如果字符串输入格式始终相同,则只需使用
split
(),这意味着它的前缀总是由数字分隔,并带有一个空格

set phoneNumberResult(value: string) {
    if (this.phoneNumberResult !== value) {
        let [phoneCode, phoneNumber] = value.split(' ');
        this.phoneCode = phoneCode;
        this.phoneNumber = phoneNumber;
        this.changed.forEach(f => f(value));
    }
}
split
在您的例子中,将返回一个数组,其中第一个元素将是被拆分字符串的左侧,第二个元素将是被拆分字符串的右侧


要玩弄的小提琴示例:

如果你只是用空的空间把它分开怎么办<代码>变量[前缀,电话号码]='+36 42534534.split('')其中
前缀
将变为+36,
电话号码
将变为42534534使用拆分:如果它是一个字符串,您可以使用拆分()如果您只是按空格拆分它呢<代码>变量[前缀,电话号码]='+36 42534534.split('')其中
前缀
将变为+36,
电话号码
将变为42534534使用拆分:如果是字符串,则可以使用拆分()