-2

So I am new to Javascript and Regular expressions and I am looking forward to do the following in the most minimal and efficient way using Javascript regular expressions:-

2 or more sequential '?' followed by an 's' and followed by a space, comma, or period, replace with an apostrophe. Else remove the sequence of 2 or more sequential '?' (don't replace with a space).

I tried doing something like this:

str.replace(/?{2,}s,/g,"'s,");
str.replace(/?{2,}s./g,"'s.");
str.replace(/?{2,}s\s/g,"'s ");

But I am not sure how to do it in one line

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89
Paul
  • 11
  • 1
  • If you want to write multiple `.replace` as chain *(in one line)*, you can do that like this `str.replace().replace().replace();` – Shafizadeh Mar 02 '16 at 20:41
  • is this the best of doing what I am trying to do? or are there better ways? – Paul Mar 02 '16 at 20:42
  • No, That's not the best approach .. I think you can do that by using just one `.replace` .. But I don't know what you want exactly .. So I cannot help you. You have to provide a few expected input/output to your question. – Shafizadeh Mar 02 '16 at 20:45
  • Inputs - ?????s, Output - 's, Input - ?????? Output - replace question marks with nothing Input - ????s. Output - 's. – Paul Mar 02 '16 at 20:46
  • Yes. We need to see some expected input/output as example to understand what are you looking for exactly. Something like the *examples* in [this question](http://stackoverflow.com/questions/34415399/how-to-extract-href-attribute-from-link-and-create-a-specific-pattern-of-that) – Shafizadeh Mar 02 '16 at 20:47

1 Answers1

0

Your regular expression can be reduced to just using a character class at the end , as it's the only part changing. You can also capture this last element and use it to replace your string if it matched.

var newStr = str.replace(/\?{2,}s([,\s.])/g,"'s$1");
slugo
  • 1,019
  • 2
  • 11
  • 22