简体   繁体   中英

Remove whitespace after a particular symbol

I've got a string which has the > symbol multiple times. After every > symbol there is a line break. How can I remove whitespaces after every > symbol in the string?

This is what I tried for spaces. But I need to remove whitespaces only after > symbol.

str.replace(/\s/g, '');

String:

<Apple is red>
<Grapes - Purple>
<Strawberries are Red>

Try this:

str.replace(/>\s/g, '>')

Demo:

 console.log(`<Apple is red> <Grapes - Purple> <Strawberries are Red>`.replace(/>\\s/g, '>'))

If you are trying to remove newline characters you can use RegExp /(>)(\\n)/g to replace second capture group (\\n) with replacement empty string ""

 var str = `<Apple is red> <Grapes - Purple> <Strawberries are Red>`; console.log(`str:${str}`); var res = str.replace(/(>)(\\n)/g, "$1"); console.log(`res:${res}`);

Use the following approach:

 var str = 'some> text > the end>', replaced = str.replace(/(\\>)\\s+/g, "$1"); console.log(replaced);

  1. You must use /m flag on your regex pattern

  2. You must use $1 capture group symbol on your replacement text

    var text = '<Apple is red>\\r\\n<Grapes - Purple>\\r\\n<Strawberries are Red>'; var regex = /(>)\\s*[\\n]/gm; var strippedText = text.replace(regex,'$1');

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