-2

hello 'this' is my'str'ing

If I have string like this, I'd like to make it all upper case if not surrounded by single quote.

hello 'this' is my'str'ing=>HELLO 'this' IS MY'str'ING

Is there a easy way I can achieve this in node perhaps using regex?

halfer
  • 19,824
  • 17
  • 99
  • 186
codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167
  • Maybe you're looking for http://stackoverflow.com/questions/5166862/javascript-regular-expression-iterator-to-extract-groups – paddy Mar 07 '17 at 22:58
  • You need a parser. – Kenneth K. Mar 07 '17 at 22:59
  • Match `([^']+)('[^']*')?` then use a _function()_ callback to join the upper of group 1 with group 2. –  Mar 07 '17 at 23:07
  • @sln Except that that fails on something like `O'Hare 'International' Airport`. – Kenneth K. Mar 07 '17 at 23:16
  • 1
    Possible duplicate of [Alternative to regex: match all instances not inside quotes](http://stackoverflow.com/questions/6462578/alternative-to-regex-match-all-instances-not-inside-quotes) – ssc-hrep3 Mar 07 '17 at 23:34
  • @ssc-hrep3 It's not a duplicate, quotes don't have the troublesome dual-role that apostrophe's do. – Regular Jo Mar 08 '17 at 02:21
  • @KennethK. - I can't read peoples minds for intent. If it's you who needs an answer, validate the regex first in a separate regex `^[^']*(?:'[^']*'[^']*)+[^']*$` –  Mar 09 '17 at 00:29

2 Answers2

1

You can use the following regular expression:

'[^']+'|(\w)

Here is a live example:

var subject = "hello 'this' is my'str'ing";
var regex = /'[^']+'|(\w)/g;
replaced = subject.replace(regex, function(m, group1) {
    if (!group1) {
        return m;
    }
    else {
        return m.toUpperCase();
    }
});

document.write(replaced);

Credit of this answer goes to zx81. For more information see the original answer of zx81.

Community
  • 1
  • 1
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
0

Since Javascript doesn't support lookbehinds, we have to use \B which matches anything a word boundary doesn't match.

In this case, \B' makes sure that ' isn't to the right of anything in \w ([a-zA-Z0-9_]). Likewise, '\B does a similar check to the left.

(?:(.*?)(?=\B'.*?'\B)(?:(\B'.*?'\B))|(.*?)$) (regex demo)

Use a callback function and check to see if the length of captures 1 or 3 is > 0 and if it is, return an uppercase on the match

**The sample uses \U and \L just to uppercase and lowercase the related matches. Your callback need not ever effect $2's case, so "Adam" can stay "Adam", etc.


Unrelated, but a note to anyone who might be trying to do this in reverse. it's much easier to the the REVERSE of this:

(\B'.+?'\B) regex demo

Regular Jo
  • 5,190
  • 3
  • 25
  • 47