简体   繁体   中英

Remove specific multiple ending characters on a string

I want to remove certain characters when they are at the end of a string. I have a working regex but the issue is the following:

My code:

var text = "some string";
text.replace(/\,$|:$|;$|-$|\($|–$|#$|\.$/, '');

So let's see the issue

If text = "that a nice ( ", then my code outputs "that a nice " , which is exactly what I want.

But if if text has multiple matches such as

text = "that a nice ( #" , then the output of my current code is: "that a nice ( " ... but I want to remove also the ( when it's at the end of the string as you can see on my regexp. I'd need to trim it so that the white space is removed but then how to remove the ( again...

The question is how to remove any unwanted characters and make sure that the new output also does not include these characters at their (new) end ? I could have 2, 3 or whatever number of unwanted characters at the end

You could use pattern: (\\s*[#(])+$

\\s*[#(] matches zero or more spaces, then one or more one of characters in square brackets, where you should list all unwanted characters. And then it matches this whole pattern on ro more times. $ matches end of string to assure that we are at the end of a string.

Demo

使用此正则表达式并尝试:

/(\s*[-,:;\(#\.])*$/

You may use a character class with + quantifier that should include \\s (whitespace):

 var text = "that a nice ( #"; text = text.replace(/[-,\\s(){}:;(#.–]+$/, ''); console.log(text); 

This will remove all unwanted character at the end and keep a space.

 var test = [ "that a nice (", "that a nice ( #", ]; console.log(test.map(function (a) { return a.replace(/[-,:;(#.–](?:\\s*[-,:;(#.–])*$/, ''); })); 

Use a character group and match it any times at the end /[(,:;\\-–#\\.\\s]*$/ :

 const sanitize = text => text.replace(/[(,:;\\-–#\\.\\s]*$/, ''); console.log(sanitize('this is a nice,:;-–#.')); console.log(sanitize('this is a nice ( ')); console.log(sanitize('this is a nice ( #')); console.log(sanitize('this is a nice (:- ')); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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