Jeff
Jeff

Reputation: 1800

Replace first occurance of char with * then the rest with a ' '

I have a sentence (this is a dumb example sentence ) that looks like this:

I_like_to_program__.

I need a function to make it look like this:

I*like to program.

I have written this expression:

var myExpression = new RegExp("\\_", "g");
return myString.replace(myExpression, " ").trim();

That'll output: "I like to program." --I'm close. I just need the first space to replace with a * to make it look like I*like to program.

Upvotes: 1

Views: 160

Answers (5)

Soarabh
Soarabh

Reputation: 2960

I first replace all _ replace with "", after doing this in we we will have program . So In second replace I am removing (program .) this space and in third replace I put * in first place.

DEMO

http://jsfiddle.net/saorabhkr/QV9qH/

Upvotes: 1

Colleen
Colleen

Reputation: 25499

The easiest thing I can think of is to do it in two steps-- replace the first instance with *, then iterate again and replace globally with " "

var myString = "I_LIKE_TO_PROGRAM";
var myExpression = new RegExp("\_");
myString = myString.replace(myExpression, "*").trim();
var newExpression = new RegExp("\_", "g");
alert(myString.replace(newExpression, " ").trim());

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382274

If you don't add g, javascript's replace default to only one replacement :

return myString.replace(/\__/, "").replace(/\_/, "*").replace(/\_/g, " ");

Upvotes: 3

enhzflep
enhzflep

Reputation: 13099

var myString = "I_like_to_program__.";
var result =  myString.replace(/\_/g, " ").replace("  ", "").replace(" ", '*');
alert(result);

Upvotes: 1

I Hate Lazy
I Hate Lazy

Reputation: 48781

mystring.replace("_", "*")
        .replace(/_/g, " ");

Or you could avoid the regex altogether like this:

mystring.replace("_", "*")
        .split("_")
        .join(" ");

Upvotes: 8

Related Questions