1/**
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15export class StringUtil {
16  static isEmpty(str: string): boolean {
17    return str == 'undefined' || !str || !/[^\s]/.test(str);
18  }
19
20  static removeSpace(str: string): string {
21    if (this.isEmpty(str)) {
22      return '';
23    }
24    return str.replace(/[\s]/g, '');
25  }
26
27  /* Obtains the result string that matches the specified substring in the original character string.
28   Only the result of the first successful match is returned.(The matching rule ignores spaces.)
29   */
30  static getMatchedString(textValue, regString): string {
31    if (this.isEmpty(textValue) || this.isEmpty(regString)) {
32      return '';
33    }
34    regString = this.removeSpace(regString);
35    let matchedTemp = '';
36
37    // spaces count
38    let k = 0;
39    for (let i = 0; i < textValue.length; i++) {
40      if (textValue.charAt(i) == regString.charAt(0)) {
41        for (let j = 0; j < regString.length; j++) {
42          if (textValue.charAt(i + k + j) == regString.charAt(j) || textValue.charAt(i + k + j) == ' ') {
43            matchedTemp = matchedTemp + textValue.charAt(i + k + j);
44            if (textValue.charAt(i + k + j) == ' ') {
45              // If the main string is a space, the substring is not counted.
46              k++;
47              j--;
48            }
49          } else {
50            k = 0;
51            matchedTemp = '';
52            break;
53          }
54          if (j == regString.length - 1) {
55            return matchedTemp;
56          }
57        }
58      }
59    }
60    return '';
61  }
62}