Underscore.js是否具备类似C++ sprintf()的字符串拼接与变量替换功能?
Hey there! Let's tackle your two questions step by step.
1. 手动实现字符串拼接并将变量替换为下划线
Depending on your exact use case, here are a couple of practical approaches:
Scenario 1: Template-based variable replacement (with underscores matching value length)
If you're working with a template string that has placeholders for variables, you can write a simple function to replace each placeholder with underscores of the same length as the original variable value:
function swapVarsWithUnderscores(templateStr, variables) { // Match placeholders like {varName} return templateStr.replace(/\{(\w+)\}/g, (match, varKey) => { // Get the original variable value (default to empty string if missing) const varValue = variables[varKey] || ''; // Return underscores equal to the value's length return '_'.repeat(varValue.length); }); } // Example usage const userTemplate = 'Profile: {name} | {role} | {department}'; const userInfo = { name: 'Alice Smith', role: 'Senior Dev', department: 'Engineering' }; const processedStr = swapVarsWithUnderscores(userTemplate, userInfo); console.log(processedStr); // Output: "Profile: __________ | _________ | ___________"
Scenario 2: Basic string concatenation + replacement
If you just need to concatenate multiple strings first, then replace specific variable markers with underscores:
// Step 1: Concatenate your base strings const partA = 'Hello, my name is '; const partB = ' and I work at '; const fullTemplate = partA + '{name}' + partB + '{company}'; // Step 2: Replace variables with underscores const finalStr = fullTemplate.replace(/\{name\}/g, '______').replace(/\{company\}/g, '________'); console.log(finalStr); // Output: "Hello, my name is ______ and I work at ________"
2. Does Underscore.js offer sprintf-like string concatenation and variable replacement?
Great question! Underscore.js doesn't have a direct equivalent to C++'s sprintf() function out of the box, but it does have powerful template utilities that can handle variable replacement (including swapping variables for underscores).
Using _.template() for variable replacement
Underscore's _.template() is designed to render dynamic templates by replacing placeholders with values. To use it for your underscore replacement needs, you just need to pass in an object where each value is a string of underscores (matching the length of your original variables, if needed):
// Define your Underscore template (uses <%= %> as default placeholders) const underscoreTemplate = _.template('User: <%= username %> | Status: <%= accountStatus %>'); // Original variable data const userData = { username: 'bob123', accountStatus: 'Active' }; // Convert values to underscores of matching length const underscoreValues = _.mapObject(userData, val => '_'.repeat(val.length)); // Render the template const result = underscoreTemplate(underscoreValues); console.log(result); // Output: "User: ______ | Status: ______"
If you need more formatted string handling (like sprintf's type specifiers), you'd have to either wrap Underscore's tools in a custom function or pair it with a dedicated sprintf library—but for basic variable replacement and underscore swapping, _.template() works perfectly.
内容的提问来源于stack exchange,提问作者sazr

