Split a number from a string in JavaScript [duplicate]

余生长醉 提交于 2020-12-30 02:36:03

问题


I'd like to split strings like

'foofo21' 'bar432' 'foobar12345'

into

['foofo', '21'] ['bar', '432'] ['foobar', '12345']

Is there an easy and simple way to do this in JavaScript?

Note that the string part (for example, foofo can be in Korean instead of English).


回答1:


Check this sample code

var inputText = "'foofo21' 'bar432' 'foobar12345'";
function processText(inputText) {
    var output = [];
    var json = inputText.split(' ');
    json.forEach(function (item) {
        output.push(item.replace(/\'/g, '').split(/(\d+)/).filter(Boolean));
    });
    return output;
}

console.log(JSON.stringify(processText(inputText)));



回答2:


Second solution:

var num = "'foofo21".match(/\d+/g);
// num[0] will be 21

var letr =  "foofo21".match(/[a-zA-Z]+/g);
/* letr[0] will be foofo.
   Now both are separated, and you can make any string as you like. */



回答3:


You want a very basic regular expression, (\d+). This will match only digits.

whole_string="lasd行書繁1234"
split_string = whole_string.split(/(\d+)/)
console.log("Text:" + split_string[0] + " & Number:" + split_string[1])


来源:https://stackoverflow.com/questions/42827884/split-a-number-from-a-string-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!