Skip to content

Add more test cases for prefer-string-raw rule#2690

Merged
sindresorhus merged 2 commits into
sindresorhus:mainfrom
som-sm:test/add-cases-for-prefer-string-raw
Jun 23, 2025
Merged

Add more test cases for prefer-string-raw rule#2690
sindresorhus merged 2 commits into
sindresorhus:mainfrom
som-sm:test/add-cases-for-prefer-string-raw

Conversation

@som-sm

@som-sm som-sm commented Jun 22, 2025

Copy link
Copy Markdown
Contributor

This PR adds a couple of new test cases that cover the following:

  • String.raw`a = '\\'`

    This covers the following check, which is currently not covered by any of the tests.

    raw.at(-2) === BACKSLASH

  •  String.raw`a = 'a\\b\''`
     String.raw`a = "a\\b\""`

    These cover the nextCharacter === quote check in the following line, which again is not currently covered.

    if (nextCharacter === BACKSLASH || nextCharacter === quote) {

  •  String.raw`a = 'a\\b\"'`

    Finally, this just highlights that if the string contains unnecessarily escaped quotes (or unnecessary escapes in general), this rule would stop complaining.

@som-sm

som-sm commented Jun 22, 2025

Copy link
Copy Markdown
Contributor Author

Also, would you be open for the following refactor?


Simplifying the following:

function unescapeBackslash(raw) {
const quote = raw.charAt(0);
raw = raw.slice(1, -1);
let result = '';
for (let position = 0; position < raw.length; position++) {
const character = raw[position];
if (character === BACKSLASH) {
const nextCharacter = raw[position + 1];
if (nextCharacter === BACKSLASH || nextCharacter === quote) {
result += nextCharacter;
position++;
continue;
}
}
result += character;
}
return result;
}

To this:

function unescapeBackslash(raw) {
	const quote = raw.charAt(0);

	return raw
		.slice(1, -1)
		.replaceAll(new RegExp(String.raw`\\([\\${quote}])`, 'g'), '$1');
}

It uses a regex to replace Backslash + Backslash with Backslash and Backslash + quote with quote.

@fisker

fisker commented Jun 23, 2025

Copy link
Copy Markdown
Collaborator

would you be open for the following refactor?

Seems safe to apply.

But please use a named group instead.

@som-sm

som-sm commented Jun 23, 2025

Copy link
Copy Markdown
Contributor Author

@fisker Sure, done in #2692.

@sindresorhus
sindresorhus merged commit 7e86a8a into sindresorhus:main Jun 23, 2025
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants