tray
tray

Reputation: 261

Regular Expression - Search and Replace

I'm new to regular expression and have come across a problem.

I want to do a search and replace on a string.

Search for an instance of -- and ' and replace it with - and `, respectively.

Example Current String: Hi'yo every--body!

Replaced String: Hi`yo every-body!

Any help would greatly be appreciated!

Upvotes: 1

Views: 704

Answers (3)

Sam Greenhalgh
Sam Greenhalgh

Reputation: 6136

@dfsq is correct, regexp is overkill for a couple of simple replaces but for reference.

var s = "Hi'yo every--body!";
s = s.replace(/'/g, "`").replace(/\-{2}/g, "-");

Upvotes: 1

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

You need.

"Hi'yo every--body!".replace(/--/g, '-').replace(/'/,'`')

Make a function

 function andrew_styler(s){return s.replace(/--/g, '-').replace(/'/,'`');}

Upvotes: 1

dfsq
dfsq

Reputation: 193271

If you want just replace -- with - use the simplest regexp:

var str = "Hi'yo every--body!";
str = str.replace(/--/g, '-');

The flag g turns the global search on, so that pattern replace all occurances.

Upvotes: 1

Related Questions