Javascript 在字符串的开头和结尾添加一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11246991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:07:12  来源:igfitidea点击:

Add a character to the beginning and end of a string

javascriptregex

提问by PepeFloyd

I am using a platform which uses a JavaScript-like syntax and allows to convert my values using regex.

我使用的平台使用类似 JavaScript 的语法并允许使用正则表达式转换我的值。

I need to add a single quote at the beginning and at the end of a string, the string will always have 9 characters.

我需要在字符串的开头和结尾添加一个单引号,该字符串将始终有 9 个字符。

I.e.:

IE:

123456789should be converted to '123456789'

123456789应该转换为 '123456789'

What expression should I use?

我应该使用什么表达?

回答by evan

You don't need a regular expression.

您不需要正则表达式。

str = "123456789";

str = "'" + str + "'";

回答by Michael Lynch

If its like Javascript you can do something like...

如果它像 Javascript 你可以做类似的事情......

var myString = "'" + oldString + "'";

Where oldString is your 123456789

哪里 oldString 是你的 123456789

回答by u3758939

Although this question was asked a little early, newly defined backticksstandard called Template Literalsfrom ES6 provides new possibility to solve this question with a simpler syntax:

虽然这个问题提早了一点,但ES6 中新定义的backticks称为Template Literals 的标准提供了用更简单的语法解决这个问题的新可能性:

const str = '123456789';
const wrapped = `'${str}'`;

回答by Penny Liu

Alternatively using lodash _.pad.

或者使用 lodash _.pad

var str = '123456789';
console.log(_.pad(str, 11, '\''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

回答by andDaviD

You can use literal \\'123456789\'.

您可以使用文字\\'123456789\'。

回答by Elise Chant

Why not just coerce to a String type:

为什么不强制转换为 String 类型:

var strValue = String(123456789);