Skip to content

Commit

Permalink
Improve quoteString and use it
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Mar 3, 2020
1 parent 16a046b commit d045ae9
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
13 changes: 6 additions & 7 deletions rules/string-content.js
@@ -1,5 +1,6 @@
'use strict';
const getDocumentationUrl = require('./utils/get-documentation-url');
const quoteString = require('./utils/quote-string');
const replaceTemplateElement = require('./utils/replace-template-element');
const escapeTemplateElementRaw = require('./utils/escape-template-element-raw');

Expand Down Expand Up @@ -81,14 +82,12 @@ const create = context => {
return;
}

let fixed = string.replace(replacement.regex, suggest);
const fixed = string.replace(replacement.regex, suggest);
if (type === 'Literal') {
const quote = node.raw[0];
fixed = fixed
.replace(new RegExp(quote, 'g'), `\\${quote}`)
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n');
problem.fix = fixer => fixer.replaceText(node, quote + fixed + quote);
problem.fix = fixer => fixer.replaceText(
node,
quoteString(fixed, node.raw[0])
);
} else {
problem.fix = fixer => replaceTemplateElement(
fixer,
Expand Down
13 changes: 10 additions & 3 deletions rules/utils/quote-string.js
@@ -1,9 +1,16 @@
'use strict';

/**
Escape apostrophe and wrap the result in single quotes.
Escape string and wrap the result in quotes.
@param {string} string - The string to be quoted.
@returns {string} - The quoted string.
@param {quote} string - The quote character.
@returns {string} - The quoted and escaped string.
*/
module.exports = string => `'${string.replace(/'/g, '\\\'')}'`;
module.exports = (string, quote = '\'') => {
const escaped = string
.replace(new RegExp(quote, 'g'), `\\${quote}`)
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n');
return quote + escaped + quote;
};

0 comments on commit d045ae9

Please sign in to comment.