RegEx noob question

N

neptune6jun44

I need to take a string and allow only the first occurrence of an
apostrophe for the validation of a city name...

Example: D'Iberville, MS

Say someone enters D'I'berville, MS by mistake..

I'm able to retain all the apostrophes with the following:

city.replace(/[^a-zA-Z0-9\'\$\,\.\#\s]/g,"");

I want to retain the first apostrophe only. I've tried adding {2,} in
with the apostrophe, but no luck.

An example of the proper way to do this would be greatly appreciated.

Thanks.
 
K

Kiran Makam

    city.replace(/[^a-zA-Z0-9\'\$\,\.\#\s]/g,"");

In string replace method, second parameter can be a function. You can
make use of this like:
-----------
var str = "D'I'ber'v'i'lle";
var myRe = /([^']*')(.*)/;

str = str.replace(myRe,
function (matchStr, strInParanthesis1, strInParanthesis2) {
return strInParanthesis1 + strInParanthesis2.replace(/'/g,
"");
}
);
-----------

Output:
"D'I'ber'v'i'lle" will become "D'Iberville"
"'DIber'v'i'lle" will become "'DIberville"

- Kiran Makam
 
D

Dr J R Stockton

I want to retain the first apostrophe only.

S = "1'2'3'4'5"
S.replace("'", "\xFF").replace(/'/g, "").replace("\xFF", "'")

There, \xFF can be replaced by any chatacter that cannot occur in the
input.

S = "1'2'3'4'5"
P = S.indexOf("'")
S = S.substring(0,P+1) + S.substring(P+1).replace(/'/g, "")
 
B

Bart Van der Donck

Dr said:
S = "1'2'3'4'5"
S.replace("'", "\xFF").replace(/'/g, "").replace("\xFF", "'")

I think this would be the most efficient, yes. If there were a single
regex, it would go like this:

/(?<=')([^']*)'/g,'$1'

or

/(?<=')(.*?)'/g,'$1'

But javascript only supports look-ahead (?=/?!) and not look-behind (?
<=/?<!); so there is no other choice than finding a workaround. It
already struck me a few times that javascript has some gaps in the
language: no regex look-behind, no reverse()-property for strings, ...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

RegEx 0
Noob question about mathematical addition vs. "string addition" in C# 1
Complex regex question 1
Clickable link conversion regex? 0
regex question 4
regex question 3
compound regex 0
Multiline regex 1

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top