Chore: Replace deprecated String.prototype.substr() (#46763)

.substr() is deprecated so we replace it with .slice() which works similarily but isn't deprecated
Signed-off-by: Tobias Speicher <rootcommander@gmail.com>
This commit is contained in:
CommanderRoot 2022-04-04 11:08:06 +02:00 committed by GitHub
parent ed140906de
commit d29b8e8858
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 37 additions and 37 deletions

View File

@ -84,7 +84,7 @@ export const getTimeZoneGroups = memoize(
return groups;
}
const group = zone.substr(0, delimiter);
const group = zone.slice(0, delimiter);
groups[group] = groups[group] ?? [];
groups[group].push(zone);

View File

@ -49,7 +49,7 @@ export function stringToMs(str: string): number {
}
const nr = parseInt(str, 10);
const unit = str.substr(String(nr).length);
const unit = str.slice(String(nr).length);
const s = 1000;
const m = s * 60;
const h = m * 60;

View File

@ -29,7 +29,7 @@ function clamp(value: number, min = 0, max = 1) {
* @beta
*/
export function hexToRgb(color: string) {
color = color.substr(1);
color = color.slice(1);
const re = new RegExp(`.{1,${color.length >= 6 ? 2 : 1}}`, 'g');
let colors = color.match(re);
@ -141,7 +141,7 @@ export function decomposeColor(color: string | DecomposeColor): DecomposeColor {
values = values.split(' ');
colorSpace = values.shift();
if (values.length === 4 && values[3].charAt(0) === '/') {
values[3] = values[3].substr(1);
values[3] = values[3].slice(1);
}
if (['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].indexOf(colorSpace) === -1) {
throw new Error(

View File

@ -87,7 +87,7 @@ export class CSVReader {
// #{columkey}#a,b,c
const idx = first.indexOf('#', 2);
if (idx > 0) {
const k = first.substr(1, idx - 1);
const k = first.slice(1, idx);
const isName = 'name' === k;
// Simple object used to check if headers match
@ -103,7 +103,7 @@ export class CSVReader {
this.data.push(this.current);
}
const v = first.substr(idx + 1);
const v = first.slice(idx + 1);
if (isName) {
this.current.addFieldFor(undefined, v);
for (let j = 1; j < line.length; j++) {

View File

@ -66,7 +66,7 @@ export function toFixed(value: number, decimals?: DecimalCount): string {
const decimalPos = formatted.indexOf('.');
const precision = decimalPos === -1 ? 0 : formatted.length - decimalPos - 1;
if (precision < decimals) {
return (precision ? formatted : formatted + '.') + String(factor).substr(1, decimals - precision);
return (precision ? formatted : formatted + '.') + String(factor).slice(1, decimals - precision + 1);
}
return formatted;

View File

@ -105,7 +105,7 @@ export class DataSourcePicker extends PureComponent<DataSourcePickerProps, DataS
if (ds) {
return {
label: ds.name.substr(0, 37),
label: ds.name.slice(0, 37),
value: ds.uid,
imgUrl: ds.meta.info.logos.small,
hideText: hideTextValue,

View File

@ -11,7 +11,7 @@ var fs = require('fs');
var githubClient_1 = tslib_1.__importDefault(require('./githubClient'));
var resolveContentType = function (extension) {
if (extension.startsWith('.')) {
extension = extension.substr(1);
extension = extension.slice(1);
}
switch (extension) {
case 'zip':

View File

@ -8,7 +8,7 @@ import { AxiosResponse } from 'axios';
const resolveContentType = (extension: string): string => {
if (extension.startsWith('.')) {
extension = extension.substr(1);
extension = extension.slice(1);
}
switch (extension) {
case 'zip':

View File

@ -197,7 +197,7 @@ const getBaseWebpackConfig: WebpackConfigurationGetter = async (options) => {
(context, request, callback) => {
const prefix = 'grafana/';
if (request.indexOf(prefix) === 0) {
return callback(null, request.substr(prefix.length));
return callback(null, request.slice(prefix.length));
}
// @ts-ignore

View File

@ -37,5 +37,5 @@ export function getNextCharacter(global?: any) {
const range = selection.getRangeAt(0);
const text = selection.anchorNode.textContent;
const offset = range.startOffset;
return text!.substr(offset, 1);
return text!.slice(offset, offset + 1);
}

View File

@ -32,7 +32,7 @@ export default function filterSpans(textFilter: string, spans: TraceSpan[] | TNi
.filter(Boolean)
.forEach((w) => {
if (w[0] === '-') {
excludeKeys.push(w.substr(1).toLowerCase());
excludeKeys.push(w.slice(1).toLowerCase());
} else {
includeFilters.push(w.toLowerCase());
}

View File

@ -35,7 +35,7 @@ export class AngularLocationWrapper {
navigationLogger('AngularLocationWrapper', false, 'Angular compat layer: hash');
if (!newHash) {
return locationService.getLocation().hash.substr(1);
return locationService.getLocation().hash.slice(1);
} else {
throw new Error('AngularLocationWrapper method not implemented.');
}

View File

@ -105,7 +105,7 @@ const kbn = {
const decimalPos = formatted.indexOf('.');
const precision = decimalPos === -1 ? 0 : formatted.length - decimalPos - 1;
if (precision < decimals) {
return (precision ? formatted : formatted + '.') + String(factor).substr(1, decimals - precision);
return (precision ? formatted : formatted + '.') + String(factor).slice(1, decimals - precision + 1);
}
}

View File

@ -25,7 +25,7 @@ export const AlertManagerPicker: FC<Props> = ({ onChange, current, disabled = fa
...getAllDataSources()
.filter((ds) => ds.type === DataSourceType.Alertmanager)
.map((ds) => ({
label: ds.name.substr(0, 37),
label: ds.name.slice(0, 37),
value: ds.name,
imgUrl: ds.meta.info.logos.small,
meta: ds.meta,

View File

@ -77,7 +77,7 @@ const columns: AlertTableColumnProps[] = [
label: 'Created',
// eslint-disable-next-line react/display-name
renderCell: ({ data: { activeAt } }) => (
<>{activeAt.startsWith('0001') ? '-' : activeAt.substr(0, 19).replace('T', ' ')}</>
<>{activeAt.startsWith('0001') ? '-' : activeAt.slice(0, 19).replace('T', ' ')}</>
),
size: '150px',
},

View File

@ -228,7 +228,7 @@ function isCombinedRuleEqualToPromRule(combinedRule: CombinedRule, rule: Rule, c
function hashQuery(query: string) {
// one of them might be wrapped in parens
if (query.length > 1 && query[0] === '(' && query[query.length - 1] === ')') {
query = query.substr(1, query.length - 2);
query = query.slice(1, -1);
}
// whitespace could be added or removed
query = query.replace(/\s|\n/g, '');

View File

@ -143,8 +143,8 @@ export function parseMatcher(matcher: string): Matcher {
throw new Error(`Invalid matcher: ${trimmed}`);
}
const [operator, idx] = operatorsFound[0];
const name = trimmed.substr(0, idx).trim();
const value = trimmed.substr(idx + operator.length).trim();
const name = trimmed.slice(0, idx).trim();
const value = trimmed.slice(idx + operator.length).trim();
if (!name) {
throw new Error(`Invalid matcher: ${trimmed}`);
}
@ -235,12 +235,12 @@ export function getWeekdayString(weekdays?: string[]): string {
.split(':')
.map((d) => {
const abbreviated = d.slice(0, 3);
return abbreviated[0].toLocaleUpperCase() + abbreviated.substr(1);
return abbreviated[0].toLocaleUpperCase() + abbreviated.slice(1);
})
.join('-');
} else {
const abbreviated = day.slice(0, 3);
return abbreviated[0].toLocaleUpperCase() + abbreviated.substr(1);
return abbreviated[0].toLocaleUpperCase() + abbreviated.slice(1);
}
})
.join(', ') ?? 'All')

View File

@ -71,7 +71,7 @@ export function setOptionImmutably<T extends object>(options: T, path: string |
if (key.endsWith(']')) {
const idx = key.lastIndexOf('[');
const index = +key.substring(idx + 1, key.length - 1);
const propKey = key.substr(0, idx);
const propKey = key.substring(0, idx);
let current = (options as Record<string, any>)[propKey];
const arr = Array.isArray(current) ? [...current] : [];
if (splat.length) {

View File

@ -82,7 +82,7 @@ export const FolderPickerTab = (props: Props) => {
cards.push({
value: `${folder}/${item.name}`,
label: item.name,
search: (idx ? item.name.substr(0, idx) : item.name).toLowerCase(),
search: (idx ? item.name.substring(0, idx) : item.name).toLowerCase(),
imgUrl: `public/${folder}/${item.name}`,
});
}

View File

@ -40,7 +40,7 @@ function Cell(props: CellProps) {
) : (
<img src={card.imgUrl} className={styles.img} />
)}
<h6 className={styles.text}>{card.label.substr(0, card.label.length - 4)}</h6>
<h6 className={styles.text}>{card.label.slice(0, -4)}</h6>
</div>
)}
</div>

View File

@ -19,7 +19,7 @@ export const SnapshotListTable: FC = () => {
const [removeSnapshot, setRemoveSnapshot] = useState<Snapshot | undefined>();
const currentPath = locationService.getLocation().pathname;
const fullUrl = window.location.href;
const baseUrl = fullUrl.substr(0, fullUrl.indexOf(currentPath));
const baseUrl = fullUrl.substring(0, fullUrl.indexOf(currentPath));
useAsync(async () => {
const response = await getSnapshots();

View File

@ -1031,5 +1031,5 @@ function withTeardown<T = any>(observable: Observable<T>, onUnsubscribe: () => v
function parseLogGroupName(logIdentifier: string): string {
const colonIndex = logIdentifier.lastIndexOf(':');
return logIdentifier.substr(colonIndex + 1);
return logIdentifier.slice(colonIndex + 1);
}

View File

@ -22,9 +22,9 @@ export function getHighlighterExpressionsFromQuery(input: string): string[] {
break;
}
// Drop terms for negative filters
const filterOperator = expression.substr(filterStart, 2);
const skip = expression.substr(filterStart).search(/!=|!~/) === 0;
expression = expression.substr(filterStart + 2);
const filterOperator = expression.slice(filterStart, filterStart + 2);
const skip = expression.slice(filterStart).search(/!=|!~/) === 0;
expression = expression.slice(filterStart + 2);
if (skip) {
continue;
}
@ -34,8 +34,8 @@ export function getHighlighterExpressionsFromQuery(input: string): string[] {
if (filterEnd === -1) {
filterTerm = expression.trim();
} else {
filterTerm = expression.substr(0, filterEnd).trim();
expression = expression.substr(filterEnd);
filterTerm = expression.slice(0, filterEnd).trim();
expression = expression.slice(filterEnd);
}
const quotedTerm = filterTerm.match(/"(.*?)"/);

View File

@ -62,7 +62,7 @@ export function lokiStreamResultToDataFrame(stream: LokiStreamResult, reverse?:
for (const [ts, line] of stream.values) {
// num ns epoch in string, we convert it to iso string here so it matches old format
times.add(new Date(parseInt(ts.substr(0, ts.length - 6), 10)).toISOString());
times.add(new Date(parseInt(ts.slice(0, -6), 10)).toISOString());
timesNs.add(ts);
lines.add(line);
uids.add(createUid(ts, labelsString, line, usedUids, refId));
@ -148,7 +148,7 @@ export function appendResponseToBufferedData(response: LokiTailResponse, data: M
// Add each line
for (const [ts, line] of stream.values) {
tsField.values.add(new Date(parseInt(ts.substr(0, ts.length - 6), 10)).toISOString());
tsField.values.add(new Date(parseInt(ts.slice(0, -6), 10)).toISOString());
tsNsField.values.add(ts);
lineField.values.add(line);
labelsField.values.add(unique);

View File

@ -142,8 +142,8 @@ function addLabelsToExpression(expr: string, invalidLabelsRegexp: RegExp) {
// Split query into 2 parts - before the invalidLabelsRegex match and after.
const indexOfRegexMatch = match.index ?? 0;
const exprBeforeRegexMatch = expr.substr(0, indexOfRegexMatch + 1);
const exprAfterRegexMatch = expr.substr(indexOfRegexMatch + 1);
const exprBeforeRegexMatch = expr.slice(0, indexOfRegexMatch + 1);
const exprAfterRegexMatch = expr.slice(indexOfRegexMatch + 1);
// Create arrayOfLabelObjects with label objects that have key, operator and value.
const arrayOfLabelObjects: Array<{ key: string; operator: string; value: string }> = [];
@ -157,7 +157,7 @@ function addLabelsToExpression(expr: string, invalidLabelsRegexp: RegExp) {
let result = exprBeforeRegexMatch;
arrayOfLabelObjects.filter(Boolean).forEach((obj) => {
// Remove extra set of quotes from obj.value
const value = obj.value.substr(1, obj.value.length - 2);
const value = obj.value.slice(1, -1);
result = addLabelToQuery(result, obj.key, value, obj.operator);
});