Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bombless/129c557042c2ee303a100b4399b11e34 to your computer and use it in GitHub Desktop.
Save bombless/129c557042c2ee303a100b4399b11e34 to your computer and use it in GitHub Desktop.
javascript parse javascript string literal
const acorn = require("acorn");

const code = `export default "hello, world";`;

const parsed = acorn.parse(code, {
  sourceType: "module",
});

const stringLiteral = parsed.body[0].declaration.arguments[0].value;

// 输出:hello, world
console.log(stringLiteral);
const esprima = require('esprima');

const code = 'var hello = "hello, world";';

const parsed = esprima.parseScript(code);

const stringLiteral = parsed.body[0].declarations[0].init.value;

// 输出:hello, world
console.log(stringLiteral);
var acorn = require("acorn");

// 解析字符串并遍历 AST
var code = "'hello world'";
var ast = acorn.parse(code);
var strings = [];
acorn.walk.simple(ast, {
  Literal(node) {
    if (typeof node.value === "string") {
      strings.push(node.value);
    }
  }
});

console.log(strings[0]); // 输出: hello world
var esprima = require("esprima");

// 解析字符串并遍历 AST
var code = "'hello world'";
var ast = esprima.parseScript(code);
var strings = [];
esprima.visit(ast, {
  Literal(node) {
    if (typeof node.value === "string") {
      strings.push(node.value);
    }
  }
});

console.log(strings[0]); // 输出: hello world
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment