RegEX to replace <div /foo> with </div> - javascript

I'm a newbie in using RegEX and I could really use some help.
I'm doing some string replacements and I currently get the output
<div /foo>
Instead of
</div>
str = "[foo][/foo]";
Regex used:
str= str.replace(/\[/g, '<div ').replace(/\]/g, '>');
Output wanted:
<div foo></div>
Can someone help me to replace the string in the right way?
Thank you very much!

Not much content to your question so I just posted something which gets the job done. Note this assumes you do not care about anything after the opening tag, it only keeps the name of the tag and replaces it by </tagname>.
var str = "<div /foo>";
var replaced = str.replace(/<(\w+).*/, '</$1>')
// "</div>"

This one could suit your needs:
\[([^\]]+)\](.*?)\[/\1\]
Replace with: <div $1>$2</div>
Visualization by Debuggex
Demo on RegExr
PS: don't forget to escape the / if using JavaScript's regex literal, i.e.:
/\[([^\]]+)\](.*?)\[\/\1\]/g

How about:
str= str.replace(/\[(.+?)\]\[\/\1\]/g, '<div $1></div>');

You can do like this also.
var str = "[foo][/foo]";
//replace <, > with [, ]
var signReplace = str.replace(/\[/g, '<').replace(/\]/g, '>');
tagReplace = signReplace.replace(/foo/g, 'div'); //replace div with foo

Related

How to replace a text plus brackets

Hi there how can I replace from this to this
var str = document.getElementById('bos').innerHTML.replace('col_nr', "");
document.getElementById('bos').innerHTML = str;
<div id="bos">
col_nr[504]
</div>
I want to be able to take only the number without brackets
You can perform more replace() to achieve your goal, demonstrated as below. Alternatively, you can use regular expression to perform your task as well.
var str = document.getElementById('bos').innerHTML.replace('col_nr[', '').replace(']', '');
document.getElementById('bos').innerHTML = str;
<div id="bos">
col_nr[504]
</div>
You could replace all not number characters.
var element = document.getElementById('bos');
element.innerHTML = element.innerHTML.replace(/\D/g, "");
<div id="bos">
col_nr[504]
</div>

Using javascript/jquery to remove text after a certain character

Is there a way to replace/remove the text only after a certain character using jQuery or Javascript? I want to remove text after the dot '.' from an element.
You can easily do it with .split() like this:
var text = 'daslkdaskldj.asdasdasd';
text.split('.')[0];
here is fiddle
var string = "Test String.Test String 2".split('.')[0];
console.log(string)
Will give you the output:
Test String
Here is a working example:
https://jsfiddle.net/zr2wg90d/
Your question is a bit unclear. But to remove all text after the first '.'(dot) This can do the trick with an input field. There are a lot of ways to achieve this. This is a solution without jQuery.
function removeAfterDot() {
var test = document.getElementById("myInput").value;
alert("String before remove: " + test);
test = test.substr(0, test.indexOf('.'));
alert("String after remove: " + test);
}
<input type="text" id="myInput" onchange=removeAfterDot();>
text.substr(0, text.indexOf('.'));
Hope this helps.
var q = 'https://stackoverflow.com/questions/';
q = q.substring(0, q.indexOf('.'));
alert(q);
Try this
var yourString = "Hello. World";
yourString.substr(0, yourString.indexOf('.'));
Will give you the following output
Hello
you can use this. split any string at the character you give it.
<p>first part . second part</p>
remove
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('a').click(function(){
var the_string = $('p').text();
var removed = the_string.split('.', 1);
$('p').text(removed);
});
</script>
for me splice works, I basically use this for removing characters after a hyphen or a comma etc.
var text = 'Tellme.more';
text.split('.')[0]);
//Consoles out -> Tellme

jQuery escape period in id

According to this page this should work. Here is the code and the JSFiddle.
<input id="id.docType" value="45"/>
<br/>
<p></p>
<input id="thevalue" />
var str = 'id.docType';
str = str.replace('.', '\\\\.');
var selector = '#' + str;
$('p').text(selector);
var x = $(selector).val();
$('#thevalue').val(x);
Any ideas why this doesn't work? I have ids that have periods and trying to use them as a selector with jQuery. jQuery's page says I should be able to escape the period with 2 back slashes but it isn't working.
Change
str = str.replace('.', '\\\\.');
to
str = str.replace('\.', '\\.');
jsFiddle example
The slash is double escaped, it only needs escaped once:
str = str.replace('.', '\\.');

Escape characters in String in a HTML page?

I have a string in the below non-escaped format in a HTML page:
<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>
What I need is to use jQuery/JavaScript to replace that string with just the link "SomeThing".
I have looked at some examples in StackOverflow, but they don't seem to work. I'm just getting started with jQuery and JavaScript, so would appreciate any help here.
Any ideas?
Try html() and text() in jquery to decode:
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var decoded = $('<div />').html(str).text();
alert($(decoded).text());
See Fiddle demo
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var helper = document.createElement('p');
// evaluate as HTML once, text now "<a href..."
helper.innerHtml = str;
// evaluate as HTML again, helper now has child element a
helper.innerHtml = helper.innerText;
// get text content only ("SomeThing")
alert(helper.innerText);
Here is a possible starting point.
Hope this gets you started!
function parseString(){
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var begin = str.indexOf('\">',0)+2; //--determine where the opening anchor tag ends
var end = str.indexOf('</a>',0); //--determine where the closing anchor tag begins
var parsedString = str.substring(begin,end); //--grab whats in between;
/*//--or all inline
var parsedString = str.substring(str.indexOf('\">',0)+2,str.indexOf('</a>',0));
*/
console.log(parsedString);
}
parseStr();

Convert tags to html entities

Is it possible to convert html tags to html entities using javascript/jquery using any way possible such as regex or some other way. If yes, then how?
Example:
<div> should be converted to <div>
Note: I am not talking about server-side languages.
Try this function for the HTML special characters:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
As you tagged with jquery, a jQuery-powered solution should work for you:
$("<div>").text("<div>bleh</div>whatever").html()
Replace the argument to the text-method with whatever markup you want to escape.
I have 2 fast and small implementations for encoding HTML safely.
You can encode all characters in your string:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
Or just target the main characters to worry about (&, inebreaks, <, >, " and ') like:
function encode(r){
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
}
var myString='Encode HTML entities!\n"Safe" escape <script></'+'script> & other tags!';
test.value=encode(myString);
testing.innerHTML=encode(myString);
/*************
* \x26 is &ampersand (it has to be first),
* \x0A is newline,
*************/
<p><b>What JavaScript Generated:</b></p>
<textarea id=test rows="3" cols="55"></textarea>
<p><b>What It Renders Too In HTML:</b></p>
<div id="testing">www.WHAK.com</div>
In JQuery:
$('<div/>').text('This is fun & stuff').html(); // evaluates to "This is fun & stuff"
http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
If you have the variable and you want to insert it on a div, you can call text().
var myVar = "<span><strong>Some vars</strong> Some var extra</span>";
$("div").text(myVar);
var d = "<div>"
d = d.replace(/<|>/g, function(chr){
return chr == "<" ? "<" : ">"
})
console.log(d)
There's a concise way of doing this using String.prototype.replace() and regular expressions as follows:
var tag = "<h1>This should </h1>be bold<h2> and big</h2>";
var escapedTag = tag.replace(/</g, "<").replace(/>/g, ">");

Categories