(javascript) 如果你有一个字符串,它是一个以数字结尾的单词。如何在单词和数字之间添加 space?

(javascript) If you had a string that was a word with a number at the end. How would you add a space between the word and the number?

例如:

let word = 'Winter4000'

const seperate = (word) => {
  ...
}

seperate(word) // output: Winter 4000

单词可以随意,数字总是在最后。

let word = 'Winter4000'
const seperate = word.split(/([0-9]+)/).join(" ")

使用正则表达式模式将其拆分以查找数字,然后将其重新连接在一起并添加 space

const word = 'Winter4000';
const result = word.match(/[^\d]+/) + ' ' + word.match(/[\d]+/);

Ian 的答案适用于大多数整数,但对于小数或带逗号的数字(例如 1,000,000),您需要一个类似

的表达式
word.split(/([0-9.,]+)/).join(" ");

所以它不会在遇到小数点或逗号时添加额外的space。

写成一个函数,

let word = 'Winter4,000.000';

const seperate = (input_word) => {
    return input_word.split(/([0-9.,]+)/).join(" ");
}

console.log(seperate(word));