简体   繁体   English

如何从字符串的开头和结尾剪掉特定字符?

[英]How can I trim a specific character off the start & end of a string?

How can I remove a specific character, a double-quote ( " ), appearing any number of times, from the start and end of a string? 如何从字符串的开头和结尾删除特定字符,双引号( " ),出现任意次数?

I had a look at string.trim() , which trims any whitespace characters, but it's not possible to provide an optional argument with " as the needle to search for. 我看了一下string.trim() ,它修剪了任何空白字符,但是不可能提供一个带有"作为搜索针的可选参数。

You can use RegEx to easily conquer this problem: 您可以使用RegEx轻松克服此问题:

myString = myString.replace(/^"+|"+$/g, '');

You can substitute the " with any character (be careful, some characters need to be escaped ). 您可以用"任何字符替换" (请注意, 某些字符需要转义 )。

Here's a demo on JSFiddle . 这是JSFiddle的演示


An explanation of the regular expression: 正则表达式的解释:

/ - start RegEx ( / ) / - 启动RegEx( /

^"+ - match the start of the line ( ^ ) followed by a quote ( " ) 1 or more times ( + ) ^"+ - 匹配行的开头( ^ )后跟引号( " )1次或多次( +

| - or - 要么

"+$ - match a quote ( " ) 1 or more times ( + ) followed by the end of the line ( $ ) "+$ - 匹配报价( " )1次或多次( + )后跟行尾( $

/ - end RegEx ( / ) / - 结束RegEx( /

g - "global" match, ie replace all g - “全局”匹配,即替换所有

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM