博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript的模板字符串,如何保持多行缩进且去除格式化空格?
阅读量:7120 次
发布时间:2019-06-28

本文共 1573 字,大约阅读时间需要 5 分钟。

JavaScript在ES6标准之后,支持了模板字符串,模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。

// 普通字符串`hello world.`// 多行字符串`helloworld.`// 字符串中嵌入变量var a = 'world';var b = `hello ${a}`;复制代码

问题描述

使用过程中往往会遇到这样一个问题,在多行字符串使用的时候,为了保证代码整齐通常会换行后缩进,但该缩进会被模板字符串认为是字符串的一部分,这里就产生了矛盾。

var a = `This is a template string.             Even though each line is indented to keep the             code neat and tidy, the white space used to indent             is not in the resulting string`;console.log(a);/* 打印结果"This is a template string.             Even though each line is indented to keep the             code neat and tidy, the white space used to indent             is not in the resulting string" */复制代码

解决方案

针对上述情况有以下几个解决方案,既可以保持代码缩进多行,又不会在结果字符串中包含格式化空格。

  1. 传统的字符串拼接+换行符
var a = `This is a template string.\n`      + `Even though each line is indented to keep the\n`复制代码
  • 优点:简单易懂
  • 缺点:拼接繁琐容易出错,没有充分利用模板字符串的优势
  1. 字符串替换
var a = (`This is a template string.             Even though each line is indented to keep the             code neat and tidy, the white space used to indent             is not in the resulting string`            ).replace(/^             /gm, '');复制代码
  • 优点:充分利用了模板字符串
  • 缺点:空格数不一致容易导致替换出错,对文本有侵入性可能会替换掉不该替换的内容,增加运算时间
  1. 变量替换
const N = "\n";var a = `This is a template string. ${           N}Even though each line is indented to keep the ${           N}code neat and tidy, the white space used to indent ${           N}is not in the resulting string`;复制代码
  • 优点:简单易懂且充分利用模板字符串的特性,和Scala中的stripMargin很像
  • 缺点:需要专门维护换行符变量

以上的方案各有优劣,综合来说第3种方案最值得使用,希望ECMAScript能够针对该点进行优化

参考资料

转载地址:http://aeiel.baihongyu.com/

你可能感兴趣的文章
# 20155224 实验四 Android程序设计
查看>>
ARP 协议 理解
查看>>
Allow windows service to "Interact with desktop"
查看>>
InitGoogleLogging坑爹
查看>>
SQL 查询间隔时间大于60s的所有数据
查看>>
*ecshop 限制文章帮助文章显示条数
查看>>
使用phpStudyy运行tipask
查看>>
c# 常用函数
查看>>
网络TCp数据的传输设计(黏包处理)
查看>>
C++ Custom Control控件 向父窗体发送对应的消息
查看>>
二十四 多重继承
查看>>
jmeter压力性能测试-多台机器并发请求
查看>>
选择编程字体
查看>>
小程序日常工作总结
查看>>
mySql学习笔记:比sql server书写要简单
查看>>
ajax封装
查看>>
例题9-6 UVa11400 Lighting System Design(DP)
查看>>
PAT1087 All Roads Lead to Rome (30)(最短路径+dfs+回溯)
查看>>
learn go function callback
查看>>
Arcgis Engine 添加一个Symbol符号样式步骤
查看>>