1

I have a string like hey! <input/>, Welcome in a template.

I need to replace every <input/> with the a JS expression this.input.

eg:

//Input
"hey! <input/>, Welcome";

Output should be:    
"hey! " + this.input + ", Welcome";

I can do a replace on the string with " + this.input + " but the problem is what if <input/> at the start or the end?

What is the best way to handle this?

Edit:

I don't want the output to be a string. I want the output to be a valid JS expression.

Valid inputs:
1) "hey! <input/>, Welcome";
2) "<input/>, Welcome";
3) "Welcome <input/>"

Outputs:
1) "hey! " + this.input + ", Welcome";
2) this.input + ", Welcome";
3) "Welcome " + this.input;
7
  • in a text editor? on a web form? where is the input coming from? Commented Jun 24, 2015 at 15:05
  • @anubhava this is not a duplicate of that question. I have to replace with a javascript expression. Commented Jun 24, 2015 at 15:07
  • @mrrogers This is in a template and i need to process such a string to output. Commented Jun 24, 2015 at 15:07
  • So like, "hey! <input/>, Welcome".replace(/<input\/>/g, '" + this.input + "'); will give you "hey! " + this.input + ", Welcome". Like that? Commented Jun 24, 2015 at 15:13
  • @thomas Yes like that. but the problem is what if <input/> is the first word in the string? Commented Jun 24, 2015 at 15:14

2 Answers 2

1

As I wrote in comments above you can use:

var input = 'foo';
var str = "hey! <input/>, Welcome";
str = str.replace(/(.*?)<input\/>(.*)/, '$1' + this.input + '$2');

console.log(str);
//=> "hey! foo, Welcome"
Sign up to request clarification or add additional context in comments.

2 Comments

Took the first valid input in the question and ran your code. Give me this: "hey! hey! <input/>, Welcome, Welcome
That's not correct testing. I am just getting hey! undefined, Welcome" since this.input is undefined. Let me put full code for you.
0
"hey! <input/>, Welcome".replace(/<input\/>/, this.input);

EDIT:

John Reisig made a blog entry about making a minimal templating language parser in javascript. It's well written and may be a good starting point for your own templating language.

4 Comments

I dont want the output to be a string like "hey this.input, Welcome.".
It should be a valid JS expression like "hey, " + this.input + ", Welcome"
Is input just a placeholder variable?
yes. replace the placeholder to create a valid js expression.

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.