1

I want to replace some codes to dom elements. For example:

[emo]sad[emo] or [emo]sad[/emo]

to

<span class='smiley medium' data-emo='" + emo + "'></span>

like

<span class='smiley medium' data-emo='sad'></span>

Is it possible?

4
  • Where do these "codes" live? Commented Mar 10, 2016 at 16:03
  • inside a <li> appended a <ul> element. i get li's innerhtml from server with ajax Commented Mar 10, 2016 at 16:05
  • is 'emo' in data-emo supposed to be a variable containing the content of [emo] tag? Commented Mar 10, 2016 at 16:07
  • yes, for example [happy] will be sent to server and get back [emo]happy[emo] to client. so i want to convert it a smiley by a span tag Commented Mar 10, 2016 at 16:09

1 Answer 1

2

How about:

var s1 = "[emo]sad[emo]";
var s2 = "[emo]sad[/emo]";

var regex = /^\[(\w+)\](.+)\[\/?(\w+)\]$/; // matches s1 and s2
var replacement = "<span class='smiley medium' data-$1='$2'></span>";
var s1HTML = s1.replace(regex,replacement);
var s2HTML = s2.replace(regex,replacement);

// now append s1HTML and s2HTML to dom

Breaking down the reg ex:

var regex = /
  ^            // start
  \[(\w+)\]    // the first [] block, match inside the []
  (.+)         // match between the [] blocks
  \[\/?(\w+)\] // the second [] block, optional "/", match inside the []
  $            // end
/;

jsbin: https://jsbin.com/nofizosebe/1/edit?js,console

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

5 Comments

This is right. However, in this particular case, you can replace \[(\w+)\] with \[emo\] and \[\/?(\w+)\] with \[\/?emo\]
Thank you for answer Jonathan and Stefano. What about "[emo]sad[emo] [emo]happy[emo]" ? Should this return me 2span tags? If so I am doing something wrong
@PcodeaXonos If you have a string like that I would recommend splitting it up into 2 separate strings and then running it through the regex.
I dont know how many [emo] will be, Its dynamic. I think I need a foreach loop?
@PcodeaXonos right, split it into an array and then use a forEach loop

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.