0

How to modify:

var a = ' z this is ok z ';
a = a.replace(/z(.*)z/, function(match){ return match.trim().toUpperCase();});
console.log(a); // output: " Z THIS IS OK Z "

I expect " ZTHIS IS OKZ ";

the uppercase work, but the trim function is ignored

2
  • in your expected output you have spaces at the very beginning and end, are those supposed to be there? Commented Jul 22, 2015 at 13:54
  • yes i just need to remove the space between Z and THIS then OK and Z Commented Jul 22, 2015 at 13:55

1 Answer 1

1

You are matching the spaces with (*). Change to:

var a = ' z this is ok z ';

// Here, you'll notice that I added the spaces next to the "z" character.
a = a.replace(/z (.*?) z/, " Z$1Z ").toUpperCase();

console.log(a); // output: " ZTHIS IS OKZ "

What this does is match everything between the "z", and then rewrites it with "Z" directly next to it.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry but this is also remove spaces in the first and last "ZTHIS IS OKZ"
I've updated my answer to include the spaces at the beginning and end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.