You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中用美元符号包裹字符串?

JavaScript实现字符串包裹方法

要把字符串比如 "student" 转换为 "$student$",可以用以下几种简单直接的方式实现:

  • 字符串拼接法
    最基础的实现方式,直接将包裹符与目标字符串拼接:

    const originalStr = "student";
    const wrappedStr = "$" + originalStr + "$";
    console.log(wrappedStr); // 输出 "$student$"
    
  • ES6模板字符串法
    利用模板字符串语法,写法更简洁直观,适合现代JavaScript开发环境:

    const originalStr = "student";
    const wrappedStr = `$${originalStr}$`;
    console.log(wrappedStr); // 输出 "$student$"
    
  • 可复用函数封装
    如果需要频繁对不同字符串使用不同包裹符,可以封装成通用函数,提升复用性:

    function wrapString(str, wrapper = "$") {
      return `${wrapper}${str}${wrapper}`;
    }
    
    // 使用示例
    console.log(wrapString("student")); // 输出 "$student$"
    console.log(wrapString("teacher", "#")); // 输出 "#teacher#"
    

内容的提问来源于stack exchange,提问作者xKralTr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:05:30