1

I'm trying to build a function, that receives a string with this format:

"hello wor**"

The * could be anywhere on the string.

It should return:

<span>hello wor</span><input type='text'></input>

So the string could be "hel** wor*d" also

and the return should be:

<span>hel</span><input type='text'> <span>wor</span><input type='text'><span>d</span>

I could do it easily with a loop on each char, but I'm looking for more elegant solutions.

I think that it could be solved with a regex, and using replace I got the "*" covered:

var text = "hello wor**";
text.replace(/\*+/g, "<input type='text'></input>");

I have not yet found a way of capturing the remaining text to render the

<span>
1
  • Thanks for your suggestions, that would work for the example string, but not for "hel** world" for example. The * could be anywhere on the string. Commented May 31, 2017 at 17:00

3 Answers 3

1

You're not using the result of the replace function. Try this:

var text = "*hel** wor*d*";
var element = text.split(/\s*\*+\s*/g);
element = "<span>"+ element.join("</span><input type='text'><span>") + "</span>";
element = element.replace(/<span><\/span>/g, "");

console.log(element);

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

4 Comments

thanks for your answer, I've edited the question to clarify some points.
@AlexTakitani this answer is just missing a "<span>" at the second replace param and a +"</span>" at the end to work
@AlexTakitani Sorry, you are right. Now it should work :)
Thank you @IlarioPierbattista very clever solution!
1
'hello wor**'.replace(/\*+/g, "<input type='text'></input>");

This returns hello wor. All you have to do is concatenate the string with the rest of the data you want, like so:

var text = "hello wor**";
text = '<span>' + text.replace(/\*+/g, '') + '</span><input type=\'text\'></input>';

1 Comment

thanks for your answer, I've edited the question to clarify some points.
0
<html>
  <head>
  </head>
  <body>
    <span id="hi">hello wor**</span> 
  </body>
</html>

i use jquery in this

$( document ).ready(function() {
        var texty = $('#hi').text();

        $('#hi').replaceWith(texty.replace(/\*+/g, "<input type='text'></input>"))
    });

1 Comment

thanks for your answer, I've edited the question to clarify some points.

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.