简体   繁体   中英

String replace with another string jquery/javascript

I have function which gets the html generated in the iframe and replaces with custom tags.For eg. <b></b> tag is replaced with [b][/b] . likewise when i press tab key , <span class="Apple-tab-span" style="white-space:pre"></span> is generated, how do i replace this with [tab][/tab] custom tag?.Please find the script which replaces bold tag, i tried replacing the whole span tag but it did not work.

Script:

function htmltoBBcode() {

var html = $("#textEditor").contents().find("body").html();
  html = html.replace(/\</gi, '[');
  html = html.replace(/\>/gi, ']');

  $("#custom-tag").text(html);


}

Any help much appreciated. Jsfiddle:

You can do it like this:

function htmltoBBcode() {
    var html = $("#textEditor").contents().find("body").html();
    html = html.replace(/\<span.*?\>/gi, '[tab]');
    html = html.replace(/\<\/span\>/gi, '[/tab]');
    html = html.replace(/\</gi, '[');
    html = html.replace(/\>/gi, ']');

    $("#custom-tag").text(html);
}

fiddle

Very easy!

 $('p').click(function(){ var t = $(this).prop('outerHTML').replace(/</g, '[').replace(/>/g, ']'); $('#custom-tag').text(t); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Click me!</p> <div id="custom-tag"></div> 

retrieving text from body tag will encode it as html, I thought you could save anywhere in a temporary textarea to decode it, than replace in the output, like this:

function decodeEntities(encodedString) {
    var textArea = document.createElement('textarea');
    textArea.innerHTML = encodedString;
    return textArea.value;
}

To replace your span tag, replace your regex like this:

html.replace(/<span>(.+)<\/span>/, '[tab]$1[/tab]');

See updated fiddle

Hope it will help! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM