0

I am making a web app, and in my admin side there's a functionality to add a dynamic input. The admin will enter a text into the textarea like:

'sample: _4_' | 'sample2: _some_'

What I want to achieve is that, I wanna replace the first ' to <p> and the second ' to </p> and when separator (|) meets, replace again the first ' to <p> and second ' to </p>. Final output would be

<p>sample: _4_</p> <p>sample2: _some_</p>

Is it possible? I really dont know the code. Thanks!

4 Answers 4

1

You can use the split and join javascript functions to replace all occurrences in a string (which is actually a char array).

Try this:

val = val.split("' | '").join("</p> <p>");
val = val.split("'").join("<p>");
val = val.slice(0,-3) + "</p>");  // Replace the last <p> to </p>
Sign up to request clarification or add additional context in comments.

4 Comments

Are you sure the string contains exactly this: ' | ' ?
Sir? Can I ask few more questions from you? What if I will do the same thing at _4_? I want to replace the first _ to <b> and the second to </b>? @KobyDouek
Replacing the X to <b>X</b> can be a bit tricky, you will need to use a regular expression - look at this answer: stackoverflow.com/questions/24834072/…. Let me know if you will need more help.
@duterte I've added an answer to your question on how to also replace _
1

You can try this solution using replace on string with split and join in combination:

val = val.split("' | '").join("<p> </p>");
val = val.replace(/^'/,"<p>").replace(/'$/,"</p>"); // Replaces first "'" with <p> and last "'" with </p>

Comments

0

Try this

var str = "'sample: _4_' | 'sample2: _some_'";

var i=0;

for(k=0;k<str.split("'").length+2;k++)
{
str=str.replace("'",function myFunction(){if(i==0) {i=1;return "<p>"; }if  (i==1){i=0;return "</p>";} });
}

str=str.replace("|"," ");

Here is the fiddle https://jsfiddle.net/j64u5em6/1/

Comments

0

You've asked for a way to also replace _ with <b>/</b>

var getReplacement = (function() {
  var replacements = {
    "'": {
      i: 0,
      elements: ["<p>", "</p>"]
    },
    "_": {
      i: 0,
      elements: ["<b>", "</b>"]
    }
  };

  return function(match) {
    var replacement = replacements[match];
    if (replacement) {
      return replacement.elements[replacement.i++ % replacement.elements.length];
    } else {
      return match;
    }
  };
}());


var str = "'sample: _4_' | 'sample2: _some_'";

console.log(str.replace(/'|_/g, getReplacement));

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.