1

i having a string variable

var text = "hello hw r u";

And i need to replace 'h' to '*' and 'l' to '-'

hw to do that..

2 Answers 2

5
text = text.replace(/h/g, "*").replace(/l/g, "-");

In answer to you comment below

* is a special character in a Reqular Expression pattern, you need to escape it using a backslash (\) character. So it would be

replace(/\*/g, 'o')

See this quick guide on JavaScript Regular Expressions

Sign up to request clarification or add additional context in comments.

2 Comments

we can't do it in a single replace call...?
You want to match two different strings and replace them with two different strings. I don't see how you could do that in one replace call
0
var string = "hello hw r u";
string = string.replace(/(h)|(l)/g,function(str,p1,p2) {
        if(p1) return '*';
        if(p2) return '-';
    });
alert(string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.