Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

som-sm
Copy link
Contributor

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

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
Copy link
Contributor Author

som-sm commented Jun 22, 2025

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
Copy link
Collaborator

fisker commented Jun 23, 2025

would you be open for the following refactor?

Seems safe to apply.

But please use a named group instead.

@som-sm
Copy link
Contributor Author

som-sm commented Jun 23, 2025

@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