I am not able to replace multiple $ signs using JavaScript/jQuery ,
my JavaScript replace code are as per bellow,
var str = $('#amt').html().replace("/\$/g","₹");
alert(str);
but it does not replace all occurrence, Please help me to replace $ by ₹ symbol.
Your regex is correct, but when wrapped it in quotes, it is no longer a RegEx, it's a string.
.replace(/\$/g, "₹");
And the HTML is not replaced it is just creating a string variable, use
$('#amt').html(function (i, oldHtml) {
return oldHtml.replace(/\$/g, "₹");
});
$('#amt').html(function(i, oldHtml) {
return oldHtml.replace(/\$/g, "₹");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="amt">
<div>Books: $150.00</div>
<div>Food: $2050.00</div>
<div>Total: $2200.00</div>
</div>
Related
I have some HTML where I've dynamically printed a bunch of elements, some containing a specific data attribute. Because my templating language can't efficiently make use of regular expressions, I need to use JavaSript (or JQuery) to select the data values, build a string, then add that string as a class to that original element.
Example of HTML:
<div class="item" data-ses-cat="This Cool Thing (Yes)"></div>
Example of Desired HTML after JavaScript:
<div class="item this-cool-thing-yes" data-ses-cat="This Cool Thing (Yes)"></div>
I just need to add a class to all tags that contain data-ses-cat then get the value for that data attribute, run regex, then add that new string as a class.
I feel like it should be fairly simple, but I haven't touched a lot of JQuery in a while.
Thanks for any help!
Remove every character that is not alphanumeric or a space, then lowercase it, then split on space, and join on dash.
$('.item[data-ses-cat]').each(function(){
var newClass = $(this).data('ses-cat')
.replace( /[^a-zA-Z0-9 ]/g, '' )
.toLowerCase()
.split( ' ' )
.join( '-' );
this.classList.add( newClass );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item" data-ses-cat="This Cool Thing (Yes)">Test</div>
And from your comments, here is a version that uses arrow functions.
$('.item[data-ses-cat]').each((index, element)=>{
var newClass = $(element).data('ses-cat')
.replace( /[^a-zA-Z0-9 ]/g, '' )
.toLowerCase()
.split( ' ' )
.join( '-' );
element.classList.add( newClass );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item" data-ses-cat="This Cool Thing (Yes)">Test</div>
A vanilla JS version of the code would look something like this:
function processElement(element) {
const clazz =
element.dataset.sesCat.toLowerCase()
.replace(/\(\)/g, '') // Remove brackets.
.replace(/ /g, '-'); // Replace spaces with dashes.
element.classList.add(clazz);
}
const sesCatElements = document.querySelectorAll('[data-ses-cat]');
sesCatElements.forEach(processElement);
Of course, you can tweak your RegExp exactly how you want it.
Here is some info on how Dataset API works.
And this, is how you work with CSS class names.
This question already has answers here:
Matching quote wrapped strings in javascript with regex
(3 answers)
Closed 2 years ago.
I have a question, how can add <span style="color: blue"> to text in quotes.
Example:
.. and he said "Hello, I am Nick"
Using regex I want to achieve this result:
.. and he said <span style="color: blue>"Hello, I am Nick"</span>
I want to know how I can do that with regular expressions. Goal is to apply color only to text inside the quotes.
Using .replaceWith() function you can add span tag between any text with quotes.
$(document).ready(function() {
$("h2"). // all p tags
contents(). // select the actual contents of the tags
filter(function(i,el){ return el.nodeType === 3; }). // only the text nodes
each(function(i, el){
var $el = $(el); // take the text node as a jQuery element
var replaced = $el.text().replace(/"(.*?)"/g,'<span class="smallcaps">"$1"</span>') // wrap
$el.replaceWith(replaced); // and replace
});
});
.smallcaps {
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>and he said "Hello, i am Nick" and "I am good"</h2>
Use String.prototype.replace() method:
var str = document.querySelector('div').textContent;
var reg = /(".*\")+/g
var s = str.replace(reg, function(m){
return '<span style="color:blue">'+m+'</span>';
})
document.querySelector('div').innerHTML = s;
<div>and he said "Hello, I am Nick", some extra</div>
You can use the String's .replace() function as follows:
(1) If you want to keep the quotes and have them inside the <span>:
var source = '---- "xxxx" ---- "xxxx" ----';
var result = source.replace(/"[^"]*"/g, '<span style="color:blue">$&</span>');
console.log(result);
$('#container').html(result);
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id="container"></div>
Notes:
The [^"] sequence in the regular expression defines a set of characters that matches all characters other than a double quote. Therefore, [^"]* matches zero or more characters that are not a double quote.
The $& in the replacement string will be replaced with the matched characters.
(2) If you do not want to keep the quotes:
var source = '---- "xxxx" ---- "xxxx" ----';
var result = source.replace(/"([^"]*)"/g, '<span style="color:blue">$1</span>');
console.log(result);
$('#container').html(result);
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id="container"></div>
The parentheses in the regular expression create a capturing group. (Notice that the quotes are not within the capturing group.)
The $1 in the replacement string will be replaced with the first capturing group.
(3) If you want to keep the quotes, but have them outside the <span>:
var source = '---- "xxxx" ---- "xxxx" ----';
var result = source.replace(/"([^"]*)"/g, '"<span style="color:blue">$1</span>"');
console.log(result);
$('#container').html(result);
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id="container"></div>
Note: This is the same as #2, but the quotes are included in the substitution string, so they are put back in the result string.
If regex is not mandatory, then try this split-map-join as well
var text = document.getElementById( "el" ).innerHTML;
function transform(input)
{
return input.split("\"").map( function(item,index){ if( index % 2 != 0 ){ item = '<span style="color: blue">' + item; } return item }).join("");
}
document.getElementById( "el" ).innerHTML = transform(text)
<div id="el">
and he said "Hello, i am Nick"
</div>
'and he said "Hello, I am Nick"'.replace(/"Hello, I am Nick"/, '<span style="color: blue">$&</span>');
I am facing problem with getting value of an element whose id contains special character as . and $ sign.
my id to element is "XS_19MAY2016_012720_311.04$_cal" I am using syntax of jQuery as:
$("#"+xyz+"_cal").val() where xyz is variable having above id.
I am getting error as:
Error: Syntax error, unrecognized expression: #XS_19MAY2016_012720_311.04$_cal.
What I doing wrong or what I need to do to correct it.
Just escape the characters:
var foo = 'XS_19MAY2016_012720_311.04$';
$('#' + foo.replace(/[.$]/g, '\\$&') + '_cal').text('foo')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="XS_19MAY2016_012720_311.04$_cal"></div>
You can use this way to do that (without symbol escaping).
$(function() {
var
id = "XS_19MAY2016_012720_311.04$_cal",
text;
text = $('[id="' + id +'"]').text();
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="XS_19MAY2016_012720_311.04$_cal">Yay!</div>
You need to tell jquery that string is absolutely an 'ID', not a class.
HTML ID attribute can't includes space, and must have at least one character. But for compatibility, better to avoid '_', '.'
Here using the Javascript builtin method, and turn the DOM node to a Jquery object. It looks redundant, but it is steady and easy to read.
$(function() {
var xyz = 'XS_19MAY2016_012720_311.04$';
e = $(document.getElementById(xyz + '_cal'));
console.log(e.text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="XS_19MAY2016_012720_311.04$_cal">
hello
</div>
I need to detect some random regular expressions, and then apply them a style to each one, something like:
Replace Match[0] with <span class='found'> Match[0]</span>
Replace Match[1] with <span class='found'> Match[1]</span>
Replace Match[n] with <span class='found'> Match[n]</span>
I tried this
.replace(randomregexp, "<span class='found'>$1</span>");
but instead of Match[0] showing, it shows $1.
my code:
$("#query, article").keyup(
function change() {
if (document.getElementById("query").value == "");
else {
texts = document.getElementById("query").value;
regexpr= new RegExp(texts,"g");
document.getElementsByTagName("article")[0].innerHTML = $("article").text().replace(regexpr, '<b class="found">$1</b>');
}
}
);
You need to use wrap function. Try something like this:
.wrap('<span class="found"></span>')
or you may access matched string by using $& like this:
.replace(randomregexp, "<span class='found'>$&</span>");
If you could post mode code it would be helpful, but try .wrap('<span class="found"></span>)
Make sure you wrap your match in ( and ). If there is no matched text it'll just show $1.
texts = '('+document.getElementById("query").value+')';
Then $1 should work for the matched substring...
'hello'.replace(/(\w+)/,"<span class='found'>$1</span>")
// Outputs: "<span class='found'>hello</span>"
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 &ersand (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, ">");