使用JavaScript获取没有版本号的名称

时间:2018-06-21 17:20:59

标签: javascript

例如“程序示例v1.2”和“程序示例V2.5”,我只想使用具有javascript功能的名称“程序示例”。怎么做?

1 个答案:

答案 0 :(得分:0)

最终,您需要的是基本的字符串操作,并且有几种方法可以实现所需的功能,每种方法都有自己的缺点和取舍。以下是几种方法:

const tests = [
    'program example v1.2',
    'program example V2.5',
    'some program v1.3',
    'some other program v7.9',
    'yet another thing v12.1',
    'the bestest ever app v0.1',
];

const methodUsingRegex = (s) => {
    return s.replace(/\s+[vV]\d+.*$/, '');
};

/*
 *    regex works as follows:
 *
 * \s+  <- look for whitespace
 * [vV] <- followed by a V (case-insensitive)
 * \d+  <- followed by a digit
 * .*   <- followed by anything whatsoever
 * $    <- until the end of the string
 *
 * this of course will break if any input string
 * doesn't exactly match this pattern, i.e.,
 *     'some executable version 3'
 *     or
 *     'some other executable v 1.5'
 *     or
 *     'yet another executable ver 9.3'
 */

const methodUsingArrayMethods = (s) => {
    const parts = s.split(' ');
    parts.pop();    // remove last element of array
    return parts.join(' ');
};

/*
 * relies on a space between the program name
 * and the version and number.
 * further relies on the version and number
 * being the last space-delimited info chunk
 * in the string.
 *
 * easily breaks if any of that is not met, i.e.,
 *     'some executable version 3'          // would return 'some executable version'
 *     or
 *     'some other executable v 1.5'        // would return 'some other executable v'
 *     or
 *     'yet another executable ver 9.3'     // would return 'yet another executable ver'
 */

console.log(tests.map(methodUsingRegex));
console.log(tests.map(methodUsingArrayMethods));

以上是ES6语法,但是由于我不知道您的项目要求,因此ES5中也是如此:

var tests = [
    'program example v1.2',
    'program example V2.5',
    'some program v1.3',
    'some other program v7.9',
    'yet another thing v12.1',
    'the bestest ever app v0.1',
];

var methodUsingRegex = function (s) {
    return s.replace(/\s+[vV]\d+.*$/, '');
};

var methodUsingArrayMethods = function (s) {
    const parts = s.split(' ');
    parts.pop();    // remove last element of array
    return parts.join(' ');
};

console.log(tests.map(methodUsingRegex));
console.log(tests.map(methodUsingArrayMethods));

如果您可以共享尝试过的一些代码和一些示例数据,则可以获得更好的答案。