0

I want to surround all "E" words in string by spaces using regexp, e.g.

'E+Error+E+E+LATTE+E' -> ' E +Error+ E + E +LATTE+ E '

My unsuccessful attempt:

node> 'E+Error+E+E+LATTE+E'.replace(new RegExp(`(^|\\W)(E)(\\W|$)`, 'gi'), '$1 $2 $3')
' E +Error+ E +E+LATTE+ E '

              ^^^ - no spaces

Or ever simple:

nesh> 'E+E+E+E+E'.replace(new RegExp(`(^|\\W)(E)(\\W|$)`, 'gi'), '$1 $2 $3')
' E +E+ E +E+ E '

Can the regex be used for a task like this?

alex_1948511
  • 6,073
  • 2
  • 20
  • 21

2 Answers2

0

Much simpler than that:

var str = 'E+Error+E+E+LATTE+E';

console.log(str.replace(/E/g, " E "));  // Replaces all "E" occurences

// Or, if you only want the "E"s that are delimited by "+"

// 1. split the string into an array at the "+" chars
// 2. enumerate that array (map)
// 3. check the array item's length to see if it is just one character (val.length === 1)
// 4. if so, return " E " to the new array created by map()
// 5. if not, return the original array item to the new array creaed by map()
// 6. Join all the items in the new array with a "+" and return that string
console.log(str.split("+").map(val => val.length === 1 ? " E " : val).join("+"));
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

Please check my fiddle.You can do it easily by jquery replace function.

var myStr='E+Error+E+E+LATTE+E';
console.log(myStr.toString().replace(/\+/g," + ").replace("E"," E").concat(" "))