What would the JavaScript regex be to minify contents of HTML. Note that I only want to remove spaces that are >2 and nothing below.
I also want to replace single quotation marks ' ' with double " "
This is what I got so far, although I'm guessing there's a more efficient way of doing this:
var findSpaces = content.match(' ') >= 2;
var findQuotes = content.match(" ' ");
content.replace(findSpaces, "" );
content.replace(findQuotes, ' " ' );
No jQuery please
In the below example all new lines \r\n or spaces between HTML tags are removed, and on the second phase the content within HTML tags is minified, so extra spaces are eliminated.
Finally trim() is used to remove spaces before & after the final resulting string.
// dummy string to minify
var s = `
<div value="a" class="a b" id="a">
<div>
foo bar
<br><br>
<span>baz</span> <i>a</i>
</div>
</div>
`
function minify( s ){
return s
.replace(/\>[\r\n ]+\</g, "><")
.replace(/(<.*?>)|\s+/g, (m, $1) => $1 ? $1 : ' ')
.trim()
}
console.log( minify(s) )
The above is also available as a gist in my collection
var s = `
<div value="a" class="a b" id="a">
<div>
foo bar
<br><br>
<span>baz</span> <i>a</i>
</div>
</div>
`
console.log(
s.replace(/\s{2,}/g, ' ').replace(/\'/g, '"')
)
should do the job for you
Related
What is the difference between parameter with quotation and parameter without quotation in Template literals in JavaScript
Why when I put quotation >> ('${key}') it does the function >> fun('${key}') while when I delete quotation >> (${key}) it doesn't do the function >> fun(${key})
what different between parameter with quotation and parameter without quotation in Template literals with JavaScript
for ( let key in states) {
console.log(key);
var n =states[key].name;
var cur = states[key].currency;
console.log()
con.innerHTML += `<div> <span>name : " ${n}
" </span> <br> <span>cur : " ${cur}
" </span> </div><br> <span>cur : " ${key}
" </span> <button onclick= fun('${key}')> select </button><hr> `
}
function fun(o) {
alert(states[o].name);
alert(states[o].currency);
}
the code above run the function >> fun('${key}')
for (let key in states) {
console.log(key);
var n = states[key].name;
var cur = states[key].currency;
console.log()
con.innerHTML += `<div> <span>name : " ${n}
" </span> <br> <span>cur : " ${cur}
" </span> </div><br> <span>cur : " ${key}
" </span> <button onclick= fun(${key})> select </button><hr> `
}
function fun(o) {
alert(states[o].name);
alert(states[o].currency);
}
It just adds ' in the final string.
The reason why this works in your example, but when you omit them it doesn't is because you are using that to generate js code inside an HTML handler.
Your keys are strings, so in js they need to be enclosed in either ' or ". When you omit them they are treated as variables and most likely you don't have variables (or constants) with that name(s).
I want to remove the spaces at the end of the class attribute in this string:
<div class="test wrapper " id="test"> " sample text " </div>
If I use
text = text.replace(/\s+"/g, '"');
then the space after sample text also will be removed and I want to keep that space.
Do you have any idea how can I do this?
Make your regex more specific
By adding class=" to your regular expression, you can narrow the scope of the replacement. Then using a capturing group () and the $n replacement pattern, you can save just the list of class names excluding any spaces:
var text = '<div class="test wrapper " id="test"> " sample test " </div>';
text = text.replace(/class="\s*(.+?)\s*"/g, 'class="$1"');
alert(text);
if you want result which looks like
"sample test"
then use this code
with js:
var str = " sample test "; var newStr = str.trim(); //
"sample test"
and with js and regular expression:
use this code:
var str = " sample test "; var newStr =
str.replace(/(^\s+|\s+$)/g,''); // "sample test"
Hi I am having the string which contains html content and I want use javascript to replace the tag <p class="MsoNormal"> with '' empty space and i want to replace corresponding closing tag </p> with <br> tag in that string.
If I use
first line:
str=str.replace(/<p class=\"MsoNormal\">/g,'');
second line: str=str.replace(/<\/p>/g,'<br>');
All the closing </p> tag get remove .But i want to replace the closing </p> tag which has the opening tag of "<p class="MsoNormal">".
The first line of script is okay of me .What should i use to replace that corresponding closing tag in the second line.
Check this: Output is what I got from your question is to replace with Empty String
var replaceTag = function(str, replaceTagString, endTagString) {
var str = '';
while(str.indexOf(replaceTagString) != -1) {
//search for </p> after my matched String
var indexOfClosingTag = str.indexOf(endTagString, str.indexOf(replaceTagString))
//Replace </p> using Substring
str = str.substr(0,indexOfClosingTag) + "<br>" + str.substr(indexOfClosingTag + endTagString.length,k.length)
//Replace your main String
str = str.replace(replaceTagString,'')
}
return str
}
var k = "<p class='MsoNormal'>something</p><p>other p tag</p><h1>I am h1</h1><p>Hello p</p><p class='MsoNormal'>Replace My Tag too</p>"
replaceTag(k, "<p class='MsoNormal'>", "</p>")
Output:
"something<p>other p tag</p><h1>I am h1</h1><p>Hello p</p>Replace My Tag too"
Concept:
string.indexOf(searchvalue,start)
Start searching for End of the Tag (P) after my current matched string position
Define a function yourself like this-->
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
And use it like this:
str = str.replaceAt(3, "</p>");
I am trying to replace quote (') with \' so as to escape escape quote or double quote in string
<ul id="list">
</ul>
<button id="sethrefbtn" onclick="setlink();">Set Link</button>
function setlink(){
var data = {
playerID : 102458,
playername: "Real Madrid's cristiano Ronalado"
}
listring= "<li><a href='SearchServlet?q=" + data.playername.replace(/'/g, "\'"); + "&playerid=" + data.playerID + "&page=1#pg0'>"+ data.playername +"</a></li>";
$("#list").append(listring);
}
Here is fiddle: fiddle
The desired output should be:
Real Madrid's cristiano Ronalado
Your problem is being caused by it being in an HTML attribute (so you need to convert it to an HTML character reference and not escape it). You should deal with that by using DOM instead of string mashing to build your HTML.
However, in this particular case, you are putting it in a URL, so you should be escaping it for URLs first.
You can do that with encodeURIComponent, but since you are building an entire query string and are using jQuery, you can use param instead.
function setlink() {
var data = {
playerid: 102458,
q: "Real Madrid's cristiano Ronalado",
page: 1
}
var url = "SearchServlet?" + $.param(data);
var li = $("<li />").append(
$("<a />").text(data.q).attr('href', url)
);
$("#list").append(li);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
</ul>
<button id="sethrefbtn" onclick="setlink();">Set Link</button>
listring= "<li><a href='SearchServlet?q=" + data.playername.replace(/'/g, "\'") + "&playerid=" + data.playerID + "&page=1#pg0'>"+ data.playername +"</a></li>";
Just replace the above statement in the code .
There is a semicolon in the middle of the statement in your code.
I can't 'echo' the ' ' closers in jQuery.
I tried this method:
$('#run').append("<pre><code class='prettyprint'>"+data+"</code></pre> <div data-ac-chart="+"'"+"bar"+"'"+" data-ac-data='data' data-ac-config='config' class='chart'></div>");
But this will show:
<div data-ac-chart="bar" data-ac-data="data" data-ac-config="config" class="chart"></div>
How to edit the jQUery code to the result will be this:
<div data-ac-chart="'bar'" data-ac-data="data" data-ac-config="config" class="chart"></div>
Not the neatest solution, but you could escape the double quotes.
<div data-ac-chart=\"'" + data + "'\"></div>
Example Here
$('#run').append("<pre><code class='prettyprint'>"+data+"</code></pre> <div data-ac-chart=\"'" + data + "'\" data-ac-data='data' data-ac-config='config' class='chart'></div>");
For a neater solution, I'd suggest checking out a JS templating engine.
Alternatively, you could also just change/add the value after you have appended the element:
Example Here
$('#run [data-ac-chart]').attr('data-ac-chart', "'" + data + "'");
Try this to add \ before the apostrophe, like this:
data-ac-chart="+"\'"+"bar"+"\'"
Josh was right with :
data-ac-chart="+\"'"+"bar"+"'\"
You can escape such characters using a backslash.
A) With single quotes around HTML attributes: (not recommended, here you have to escape the created attribute value)
var output = "<div data-ac-chart='\\\'bar\\\'' data-ac-data='data' data-ac-config='config' class='chart'></div>";
The multitude of backslashes is required here to mask the backslash and single quote inside the attribute from JavaScript. JS then outputs HTML with escaped attribute values:
"<div data-ac-chart='\'bar\'' data-ac-data='data' data-ac-config='config' class='chart'></div>"
B) With double quotes around HTML attributes: (recommended, write beautiful markup and everything will work out :-)
var output = '<div data-ac-chart="\'bar\'" data-ac-data="data" data-ac-config="config" class="chart"></div>';
C) A more readable approach using placeholders and string replacement:
var output = '<div data-ac-chart="{chart}" data-ac-data="{data}" data-ac-config="{config}" class="chart"></div>'
.replace( '{chart}', '\'bar\'' )
.replace( '{data}', 'data' )
.replace( '{config}', 'config' );
Concatenating strings is cumbersome and as you experience quite difficult to debug. That's why I recommend using a template approach as supported by underscorejs:
<!-- in your HTML -->
<script type="text/template" id="template">
<div>
<pre>
<code class='prettyprint'>
<%=data%>
</code>
</pre>
<div data-ac-chart='bar' data-ac-data='data' data-ac-config='config' class='chart'>
</div>
</div>
</script>
/* in your javascript */
$('#run').append(_.template($("#template").html())({
data : "var function(x) = { some code };"
}));
Make sure to load the underscorejs library. A working example is available in this jsfiddle