Regex - Combine regular expressions - Beginning and end of string

时间:2016-07-11 20:28:40

标签: javascript regex replace

I have two examples of what I need with two differents scenarios:

1. The first one:

If I have this simple string:

var message = "Hello World";

and I want this result with regular expressions:

'Hello World'

I know I can do:

message.replace(/^/, "'").replace(/$/, "'");

My question: How I can do it to make it with one regex. I mean, something like this: (of course, this doesn't work):

message.replace(/(^|$)/, "'");

2. The second one:

Again the simple string:

var message = "Hello World";

and I want this result with regular expressions:

#Hola Mundo%

And of course, I can do:

message.replace(/^/, "#").replace(/$/, "%");

And the same question: How I can do it to make it with one regex?

I know that this is a simple question, but it could be glad to have the answer.

1 个答案:

答案 0 :(得分:1)

The most appropriate way to do what you need is using string concatenation.

If you want to learn regex:


1. message.replace(/^|$/g, "'"); - you need to use /g to perform a global search and replace

Explanation:

  • ^ - start of string
  • | - or
  • $ - end of string
  • /g - perform global search and replace

See the regex demo

2. message.replace(/^[^]*$/, "#$&%") or message.replace(/^[\s\S]*$/, "#$&%")

Explanation:

  • ^ - start of string
  • [^]* - zero or more any characters (in JS, [^] means not nothing) (this can be replaced with [\s\S]* / [\w\W]* / [\d\D]* to match any characters from the BMP plane)
  • $ - end of string.

See this regex demo

The $& in the replacement pattern is the backreference to the whole match. $1 references Group 1, i.e. the first (...) capturing group value if it is defined in the pattern, but if you need to refer to the whole match, you should use $& construct.