Home > Net >  Typescript: Can't do string replacement
Typescript: Can't do string replacement

Time:01-03

I'm not familiar with typescript. I'm trying to delete the string https://i.pximg.net and https://source.pixiv.net but I'm getting this error when I try do a string replacement with typescript

ERROR in
/var/www/type.adoreanime.com/htdocs/pixiv.moe/src/utils/api.ts
  121:59  error  Replace `"https://i.pximg.net"|"https://source.pixiv.net",·''` with `⏎······'https://i.pximg.net'·|·'https://source.pixiv.net',⏎······''⏎····`  prettier/prettier
  163:3   error  Insert `⏎`                                                                                                                                      prettier/prettier

✖ 2 problems (2 errors, 0 warnings)
  2 errors and 0 warnings potentially fixable with the `--fix` option.

this is the code:

export const proxyImage = (url: string) => {
  if (!url) {
    return url;
  }
  const regex = /^https?:\/\/(i\.pximg\.net)|(source\.pixiv\.net)/i;
  if (regex.test(url)) {
    url = `https://img.adoreanime.com/image/${url.replace("https://i.pximg.net"|"https://source.pixiv.net", '')}`;
    if (
      process.env.NODE_ENV !== 'test' &&
      document.body.classList.contains('supports-webp') &&
      (url.indexOf('.png') > -1 ||
        url.indexOf('.jpg') > -1 ||
        url.indexOf('.jpeg') > -1)
    ) {
      url = `${url}@progressive.webp`;
    }
  }

  return url;
};

can anyone help me fix my typos or errors?

CodePudding user response:

This is not a TypeScript issue, it's a prettier issue.

It's telling you that the line is too long, and you should break up that line to make it more readable. means newline.

But a better approach might be to put the string to be removed into its own variable.

  if (regex.test(url)) {
    const trimOut = "https://i.pximg.net"|"https://source.pixiv.net";
    url = `https://img.adoreanime.com/image/${url.replace(trimOut, '')}`;

But also, I'm pretty sure

url.replace("https://i.pximg.net"|"https://source.pixiv.net",

is not what you wanted - "https://i.pximg.net"|"https://source.pixiv.net" will evaluate to 0. Did you mean to use a regular expression?

  if (regex.test(url)) {
    const trimOut = /https:\/\/i\.pximg\.net|https:\/\/source\.pixiv\.net/g;
    url = `https://img.adoreanime.com/image/${url.replace(trimOut, '')}`;

CodePudding user response:

This is a linter error, it is asking you to leave some space to make the code more readable. Replace the line where you are setting the url to this:

url = `https://img.adoreanime.com/image/${url.replace(
    'https://i.pximg.net'|'https://source.pixiv.net',
    ''
)}`;

It is also asking you to place a newline at the bottom of the file.

The last line of that error is giving you an option to run your linter with the '--fix' flag. Give that a go to solve some of the pesky lint errors.

  • Related