简体   繁体   中英

Remove all occurrences of a character except the first one in string with javascript

I have this string: "# abc # def #" .

I want to keep the first # and remove the following occurring # .

So the expected output would be: "# abc def " .

I use this and it works, but it feels like an ugly hack:

"# abc # def #".replace("#", "[TEMP]").replace(/#/ig, "").replace("[TEMP]", "#")

It would fail if [TEMP] exists in the string. Not a big risk, but anyway.

The other way I can think of would be to iterate the string char by char, but I feel I'm missing out on a simpler more obvious way.

If it's always at the beginning, you could do something like this:

 const result = '# A # B # C'.replace(/(?!^)#/g, ''); console.log(result); 

This will replace every # that doesn't have the start of the string right next to it.

If it's not always at the beginning of your string, probably the easiest method would be to use the callback form of replace() :

 const result = 'SOME STUFF # A # B # C MORE STUFF'.replace(/#/g, (val, index, str) => index === str.indexOf('#') ? val : ''); console.log(result); 

Basically, this approach will get all of the # . Then we just compare it's index, and if it's the index of the first one, we won't replace it. Otherwise, we will.

If you wanted to clean it up a bit, you can avoid having the indexOf() check saved before looping. This would help if the strings are long or if you need to do it a ton (it's a trivial gain on small sets):

 const cleanHashes = str => { const firstIndex = str.indexOf('#'); return str.replace(/#/g, (v, i) => i === firstIndex ? v : ''); } console.log(cleanHashes('# A # B # C')); console.log(cleanHashes('SOME STUFF # A # B # C MORE STUFF')); 

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