简体   繁体   English

仅当 % 出现在字符串的第一个或最后一个时,如何从字符串中删除 %

[英]How to remove % from the string only if the % is present in first or last of a string

I want to remove the % character from my string if the % character present in the string, then it should check whether it is in the beginning or end then it should trim the value then the provide the result.如果字符串中存在%字符,我想从字符串中删除%字符,然后它应该检查它是在开头还是结尾,然后它应该修剪值然后提供结果。

Eg: var str = "Value%" or "%Value" or "%Value%"
The result should be = Value.
Eg: var str="Va%ue"
The result should be =Va%ue.
Eg: var str= "Value"
The result should be = Value.

Thanks in Advance提前致谢

str = (str[0] == '%' || str.endsWith('%')? str.replace(/%/g, '') : str);

Check if the string starts or ends with % before replacing在替换之前检查字符串是否以%开头或结尾

Your regex basically needs to have two alternatives combined with an 'or' sign.您的正则表达式基本上需要有两个选项与一个“或”符号相结合。 You use ^ to signal beginning and $ to signal ending, then combine them with |您使用^表示开始,使用$表示结束,然后将它们与| . .

The regex for percent lookup: ^%|%$ .百分比查找的正则表达式: ^%|%$

If you put that in to the replace() function and add the global lookup flag g , you can easily achieve what you're looking for:如果将其放入replace() function 并添加全局查找标志g ,则可以轻松实现所需的内容:

const percentLookupRegex = /^%|%$/g;

str.replace(percentLookupRegex, '');

Here's a live example: https://regex101.com/r/nAK64n/2这是一个活生生的例子: https://regex101.com/r/nAK64n/2

If you want to use regex then you should look into the anchors ^ and $如果你想使用正则表达式,那么你应该查看^$

Eg.例如。

str.replace(/^%/, '');

Will replace % in the beginning of the line with nothing.将替换%在行的开头什么都没有。

An alternative approach is to use startsWith and endsWith and then slice the string appropriately:另一种方法是使用startsWithendsWith ,然后适当地对字符串进行切片

if (str.startsWith('%') {
   str = str.slice(1);
}

Removing a % at the end of the string is left as an exercise for the reader删除字符串末尾的%作为练习留给读者

str = (str.indexOf('%') === 0) ? str.substring(1) : str; // check for first character
str = (str.lastIndexOf('%') === (str.length - 1)) ? str.substring(0, str.length - 1) : str; //check for last character

This will only check for first and last character and remove only those这只会检查第一个和最后一个字符并只删除那些

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

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