0

I want to replace @parm1,@parm2,@parm3... etc with comma separated values using regular. how can i do this ?

Example

Input Data

My Name is @parm1 and My father Name is @parm2 and also my nick name is @parm1 and i live in @parm3

Replace with

James,Nortain,TEST Address

Result

My Name is James and My father Name is Nortain and also my nick name is @parm1 and i live in TEST Address

2
  • 2
    And what have you tried? Commented Jun 16, 2015 at 8:13
  • @putvande i am new and i do it using loop,but its not working so i want to do it using Regx Commented Jun 16, 2015 at 8:23

2 Answers 2

4

Try:

var str = "My Name is @parm1 and My father Name is @parm2 and also my nick name is @parm1 and i live in @parm3";
var values = "James,Nortain,TEST Address".split(",");
var result = str.replace(/@parm(\d+)/gi, function(a,b){
    return values[b-1] || a
});

document.write(result)

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

Comments

2

This will replace each of the name separated by , using for:

var str = 'My Name is @parm1 and My father Name is @parm2 and also my nick name is @parm1 and i live in @parm3';

var strName = 'James,Nortain,TEST Address';

var names = strName.split(',');

for (var i = 0; i < names.length; i++) {
    str = str.replace('@parm' + (i + 1), names[i]);
}

alert(str);

Demo: http://jsfiddle.net/tusharj/4cq08hbc/

1 Comment

Yeah - that's better. Also more correct than the other answer posted, as the OP's example result didn't replace the second @parm1 value (whether that's intentional or not...?!)

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.