How to unescape amp; in JavaScript - javascript

Say I have this string java&script, how can I convert this to java&script?
In the console of Google Chrome this doesn't work
var str="java&script";
var str_esc=escape(str);
var str_unc = unescape(str_esc)
console.log(str_esc)
console.log(str_unc)
but this seems to work just fine
<!DOCTYPE html>
<html>
<body>
<script>
var str="java&script";
var str_esc=escape(str);
document.write(str_esc + "<br>")
document.write(unescape(str_esc))
</script>
</body>
</html>
Thank you for your help

You could decode the entity with a function that drops the string into a textarea, and then pulls the value from that, like so:
function htmlEntityDecode(str){
var txt = document.createElement('textarea');
txt.innerHTML = str;
return txt.value;
}
var str = htmlEntityDecode("java&script");
console.log( str );
Or even simpler, if it really is just that one case, why not just use a simple .replace() method on it?
var str = 'java&script';
str = str.replace('&', '&');
console.log( str );
But if you have more than one instance, you would need to have a global replace:
var str = 'java & script and script & java';
str = str.replace(/&/g, '&');
console.log( str );

A simple solution to convert from an input string of say "java&script" to "java&script" can be achieved via the regular expression & passed to the the string#replace method:
var inputStr="java&script&jj";
/*
match any occourance of & in the string and replace
with &. Use the gi to cause replacement to happen irrespective
of case (i) and globally across all occurances of &
in the string (g).
*/
var unescapedStr = inputStr.replace(/&/gi, '&');
console.log(unescapedStr);

Related

replace number from the middle using javascript / node js

var str = "demo-test-1-0-4_testing.pdf";
I have a string i want to replace with word verified
so my expected value look like this
str= demo-test-verified_testing.pdf
I can do this if the numbers are written in last like this
var str = "demo-test-1-0-1";
str = str.replace(/(?!(-| |_))(\d|-|\.)+\s*$/, "verified");
console.log(str);
but in middle I don't know
as my expected value is like this demo-test-verified_testing.pdf as i want to replace 1-0-1 i can use replace function but every time version get updated so number get changed that's why i cant use replace function
This should be enough:
var str = "demo-test-1-0-4_testing.pdf";
str = str.replace(/(-\d+)+/,"-verified")
console.log(str)
str = "demo-test-1-0-1"
str = str.replace(/(-\d+)+/,"-verified")
console.log(str)
var str = "demo-test-1-0-41_testing.pdf";
str = str.replace(/(-\d+)+/,"-verified")
console.log(str)

Javascript: Convert chars like ' to UTF8 [duplicate]

This question already has answers here:
Unescape HTML entities in JavaScript?
(33 answers)
Closed 5 years ago.
How do I encode and decode HTML entities using JavaScript or JQuery?
var varTitle = "Chris&apos; corner";
I want it to be:
var varTitle = "Chris' corner";
I recommend against using the jQuery code that was accepted as the answer. While it does not insert the string to decode into the page, it does cause things such as scripts and HTML elements to get created. This is way more code than we need. Instead, I suggest using a safer, more optimized function.
var decodeEntities = (function() {
// this prevents any overhead from creating the object each time
var element = document.createElement('div');
function decodeHTMLEntities (str) {
if(str && typeof str === 'string') {
// strip script/html tags
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
return decodeHTMLEntities;
})();
http://jsfiddle.net/LYteC/4/
To use this function, just call decodeEntities("&") and it will use the same underlying techniques as the jQuery version will—but without jQuery's overhead, and after sanitizing the HTML tags in the input. See Mike Samuel's comment on the accepted answer for how to filter out HTML tags.
This function can be easily used as a jQuery plugin by adding the following line in your project.
jQuery.decodeEntities = decodeEntities;
You could try something like:
var Title = $('<textarea />').html("Chris&apos; corner").text();
console.log(Title);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
JS Fiddle.
A more interactive version:
$('form').submit(function() {
var theString = $('#string').val();
var varTitle = $('<textarea />').html(theString).text();
$('#output').text(varTitle);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
<fieldset>
<label for="string">Enter a html-encoded string to decode</label>
<input type="text" name="string" id="string" />
</fieldset>
<fieldset>
<input type="submit" value="decode" />
</fieldset>
</form>
<div id="output"></div>
JS Fiddle.
Like Robert K said, don't use jQuery.html().text() to decode html entities as it's unsafe because user input should never have access to the DOM. Read about XSS for why this is unsafe.
Instead try the Underscore.js utility-belt library which comes with escape and unescape methods:
_.escape(string)
Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.
_.escape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
_.unescape(string)
The opposite of escape, replaces &, <, >, ", ` and ' with their unescaped counterparts.
_.unescape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
To support decoding more characters, just copy the Underscore unescape method and add more characters to the map.
Original author answer here.
This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
Example: http://jsfiddle.net/k65s3/
Input:
Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
Output:
Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
Here's a quick method that doesn't require creating a div, and decodes the "most common" HTML escaped chars:
function decodeHTMLEntities(text) {
var entities = [
['amp', '&'],
['apos', '\''],
['#x27', '\''],
['#x2F', '/'],
['#39', '\''],
['#47', '/'],
['lt', '<'],
['gt', '>'],
['nbsp', ' '],
['quot', '"']
];
for (var i = 0, max = entities.length; i < max; ++i)
text = text.replace(new RegExp('&'+entities[i][0]+';', 'g'), entities[i][1]);
return text;
}
here is another version:
function convertHTMLEntity(text){
const span = document.createElement('span');
return text
.replace(/&[#A-Za-z0-9]+;/gi, (entity,position,text)=> {
span.innerHTML = entity;
return span.innerText;
});
}
console.log(convertHTMLEntity('Large < £ 500'));
Inspired by Robert K's solution, this version does not strip HTML tags, and is just as secure.
var decode_entities = (function() {
// Remove HTML Entities
var element = document.createElement('div');
function decode_HTML_entities (str) {
if(str && typeof str === 'string') {
// Escape HTML before decoding for HTML Entities
str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';');
element.innerHTML = str;
if(element.innerText){
str = element.innerText;
element.innerText = '';
}else{
// Firefox support
str = element.textContent;
element.textContent = '';
}
}
return unescape(str);
}
return decode_HTML_entities;
})();
jQuery provides a way to encode and decode html entities.
If you use a "<div/>" tag, it will strip out all the html.
function htmlDecode(value) {
return $("<div/>").html(value).text();
}
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
If you use a "<textarea/>" tag, it will preserve the html tags.
function htmlDecode(value) {
return $("<textarea/>").html(value).text();
}
function htmlEncode(value) {
return $('<textarea/>').text(value).html();
}
To add yet another "inspired by Robert K" to the list, here is another safe version which does not strip HTML tags. Instead of running the whole string through the HTML parser, it pulls out only the entities and converts those.
var decodeEntities = (function() {
// this prevents any overhead from creating the object each time
var element = document.createElement('div');
// regular expression matching HTML entities
var entity = /&(?:#x[a-f0-9]+|#[0-9]+|[a-z0-9]+);?/ig;
return function decodeHTMLEntities(str) {
// find and replace all the html entities
str = str.replace(entity, function(m) {
element.innerHTML = m;
return element.textContent;
});
// reset the value
element.textContent = '';
return str;
}
})();
Inspired by Robert K's solution, strips html tags and prevents executing scripts and eventhandlers like: <img src=fake onerror="prompt(1)">
Tested on latest Chrome, FF, IE (should work from IE9, but haven't tested).
var decodeEntities = (function () {
//create a new html document (doesn't execute script tags in child elements)
var doc = document.implementation.createHTMLDocument("");
var element = doc.createElement('div');
function getText(str) {
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
return str;
}
function decodeHTMLEntities(str) {
if (str && typeof str === 'string') {
var x = getText(str);
while (str !== x) {
str = x;
x = getText(x);
}
return x;
}
}
return decodeHTMLEntities;
})();
Simply call:
decodeEntities('<img src=fake onerror="prompt(1)">');
decodeEntities("<script>alert('aaa!')</script>");
Here is a full version
function htmldecode(s){
window.HTML_ESC_MAP = {
"nbsp":" ","iexcl":"¡","cent":"¢","pound":"£","curren":"¤","yen":"¥","brvbar":"¦","sect":"§","uml":"¨","copy":"©","ordf":"ª","laquo":"«","not":"¬","reg":"®","macr":"¯","deg":"°","plusmn":"±","sup2":"²","sup3":"³","acute":"´","micro":"µ","para":"¶","middot":"·","cedil":"¸","sup1":"¹","ordm":"º","raquo":"»","frac14":"¼","frac12":"½","frac34":"¾","iquest":"¿","Agrave":"À","Aacute":"Á","Acirc":"Â","Atilde":"Ã","Auml":"Ä","Aring":"Å","AElig":"Æ","Ccedil":"Ç","Egrave":"È","Eacute":"É","Ecirc":"Ê","Euml":"Ë","Igrave":"Ì","Iacute":"Í","Icirc":"Î","Iuml":"Ï","ETH":"Ð","Ntilde":"Ñ","Ograve":"Ò","Oacute":"Ó","Ocirc":"Ô","Otilde":"Õ","Ouml":"Ö","times":"×","Oslash":"Ø","Ugrave":"Ù","Uacute":"Ú","Ucirc":"Û","Uuml":"Ü","Yacute":"Ý","THORN":"Þ","szlig":"ß","agrave":"à","aacute":"á","acirc":"â","atilde":"ã","auml":"ä","aring":"å","aelig":"æ","ccedil":"ç","egrave":"è","eacute":"é","ecirc":"ê","euml":"ë","igrave":"ì","iacute":"í","icirc":"î","iuml":"ï","eth":"ð","ntilde":"ñ","ograve":"ò","oacute":"ó","ocirc":"ô","otilde":"õ","ouml":"ö","divide":"÷","oslash":"ø","ugrave":"ù","uacute":"ú","ucirc":"û","uuml":"ü","yacute":"ý","thorn":"þ","yuml":"ÿ","fnof":"ƒ","Alpha":"Α","Beta":"Β","Gamma":"Γ","Delta":"Δ","Epsilon":"Ε","Zeta":"Ζ","Eta":"Η","Theta":"Θ","Iota":"Ι","Kappa":"Κ","Lambda":"Λ","Mu":"Μ","Nu":"Ν","Xi":"Ξ","Omicron":"Ο","Pi":"Π","Rho":"Ρ","Sigma":"Σ","Tau":"Τ","Upsilon":"Υ","Phi":"Φ","Chi":"Χ","Psi":"Ψ","Omega":"Ω","alpha":"α","beta":"β","gamma":"γ","delta":"δ","epsilon":"ε","zeta":"ζ","eta":"η","theta":"θ","iota":"ι","kappa":"κ","lambda":"λ","mu":"μ","nu":"ν","xi":"ξ","omicron":"ο","pi":"π","rho":"ρ","sigmaf":"ς","sigma":"σ","tau":"τ","upsilon":"υ","phi":"φ","chi":"χ","psi":"ψ","omega":"ω","thetasym":"ϑ","upsih":"ϒ","piv":"ϖ","bull":"•","hellip":"…","prime":"′","Prime":"″","oline":"‾","frasl":"⁄","weierp":"℘","image":"ℑ","real":"ℜ","trade":"™","alefsym":"ℵ","larr":"←","uarr":"↑","rarr":"→","darr":"↓","harr":"↔","crarr":"↵","lArr":"⇐","uArr":"⇑","rArr":"⇒","dArr":"⇓","hArr":"⇔","forall":"∀","part":"∂","exist":"∃","empty":"∅","nabla":"∇","isin":"∈","notin":"∉","ni":"∋","prod":"∏","sum":"∑","minus":"−","lowast":"∗","radic":"√","prop":"∝","infin":"∞","ang":"∠","and":"∧","or":"∨","cap":"∩","cup":"∪","int":"∫","there4":"∴","sim":"∼","cong":"≅","asymp":"≈","ne":"≠","equiv":"≡","le":"≤","ge":"≥","sub":"⊂","sup":"⊃","nsub":"⊄","sube":"⊆","supe":"⊇","oplus":"⊕","otimes":"⊗","perp":"⊥","sdot":"⋅","lceil":"⌈","rceil":"⌉","lfloor":"⌊","rfloor":"⌋","lang":"〈","rang":"〉","loz":"◊","spades":"♠","clubs":"♣","hearts":"♥","diams":"♦","\"":"quot","amp":"&","lt":"<","gt":">","OElig":"Œ","oelig":"œ","Scaron":"Š","scaron":"š","Yuml":"Ÿ","circ":"ˆ","tilde":"˜","ndash":"–","mdash":"—","lsquo":"‘","rsquo":"’","sbquo":"‚","ldquo":"“","rdquo":"”","bdquo":"„","dagger":"†","Dagger":"‡","permil":"‰","lsaquo":"‹","rsaquo":"›","euro":"€"};
if(!window.HTML_ESC_MAP_EXP)
window.HTML_ESC_MAP_EXP = new RegExp("&("+Object.keys(HTML_ESC_MAP).join("|")+");","g");
return s?s.replace(window.HTML_ESC_MAP_EXP,function(x){
return HTML_ESC_MAP[x.substring(1,x.length-1)]||x;
}):s;
}
Usage
htmldecode("∑ >€");
Injecting untrusted HTML into the page is dangerous as explained in How to decode HTML entities using jQuery?.
One alternative is to use a JavaScript-only implementation of PHP's html_entity_decode (from http://phpjs.org/functions/html_entity_decode:424). The example would then be something like:
var varTitle = html_entity_decode("Chris&apos; corner");
A more functional approach to #William Lahti's answer:
var entities = {
'amp': '&',
'apos': '\'',
'#x27': '\'',
'#x2F': '/',
'#39': '\'',
'#47': '/',
'lt': '<',
'gt': '>',
'nbsp': ' ',
'quot': '"'
}
function decodeHTMLEntities (text) {
return text.replace(/&([^;]+);/gm, function (match, entity) {
return entities[entity] || match
})
}
I know I'm a bit late to the game, but I thought I might provide the following snippet as an example of how I decode HTML entities using jQuery:
var varTitleE = "Chris&apos; corner";
var varTitleD = $("<div/>").html(varTitleE).text();
console.log(varTitleE + " vs. " + varTitleD);​​​​​​​​​​​
Don't forget to fire-up your inspector/firebug to see the console results -- or simply replace console.log(...) w/alert(...)
That said, here's what my console via the Google Chrome inspector read:
Chris&apos; corner vs. Chris' corner
Because #Robert K and #mattcasey both have good code, I thought I'd contribute here with a CoffeeScript version, in case anyone in the future could use it:
String::unescape = (strict = false) ->
###
# Take escaped text, and return the unescaped version
#
# #param string str | String to be used
# #param bool strict | Stict mode will remove all HTML
#
# Test it here:
# https://jsfiddle.net/tigerhawkvok/t9pn1dn5/
#
# Code: https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d
###
# Create a dummy element
element = document.createElement("div")
decodeHTMLEntities = (str) ->
if str? and typeof str is "string"
unless strict is true
# escape HTML tags
str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';')
else
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '')
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '')
element.innerHTML = str
if element.innerText
# Do we support innerText?
str = element.innerText
element.innerText = ""
else
# Firefox
str = element.textContent
element.textContent = ""
unescape(str)
# Remove encoded or double-encoded tags
fixHtmlEncodings = (string) ->
string = string.replace(/\&#/mg, '&#') # The rest, for double-encodings
string = string.replace(/\"/mg, '"')
string = string.replace(/\&quote;/mg, '"')
string = string.replace(/\_/mg, '_')
string = string.replace(/\'/mg, "'")
string = string.replace(/\"/mg, '"')
string = string.replace(/\>/mg, '>')
string = string.replace(/\</mg, '<')
string
# Run it
tmp = fixHtmlEncodings(this)
decodeHTMLEntities(tmp)
See https://jsfiddle.net/tigerhawkvok/t9pn1dn5/7/ or https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d (includes compiled JS, and is probably updated compared to this answer)
To do it in pure javascript without jquery or predefining everything you can cycle the encoded html string through an elements innerHTML and innerText(/textContent) properties for every decode step that is required:
<html>
<head>
<title>For every decode step, cycle through innerHTML and innerText </title>
<script>
function decode(str) {
var d = document.createElement("div");
d.innerHTML = str;
return typeof d.innerText !== 'undefined' ? d.innerText : d.textContent;
}
</script>
</head>
<body>
<script>
var encodedString = "<p>name</p><p><span style=\"font-size:xx-small;\">ajde</span></p><p><em>da</em></p>";
</script>
<input type=button onclick="document.body.innerHTML=decode(encodedString)"/>
</body>
</html>
I think that is the exact opposite of the solution chosen.
var decoded = $("<div/>").text(encodedStr).html();
Try it :)

Add to current string using javascript

I would like to add to the current string using javascript. Currently, It is working fine but I am doing it in a very dirty way currently. I am basically replacing the WHOLE string instead of just adding to it. Is there a way that I can just add a comma and continue my string?
JS:
var mystring = "'bootstrap'"
console.log(mystring.replace(/bootstrap/g , "'bootstrap', 'bootstrap2', 'bootstrap3'"));
JSFiddle
You can add to the end of a string by using the +=operator. See the docs regarding string operators.
var mystring = "'bootstrap'"
mystring += ", 'bootstrap2'";
mystring += ", 'bootstrap3'";
console.log(mystring);
You can concatenate( + operator ) instead of replace if you just want the second string to get appended to the first string.
var mystring = "'bootstrap'"
var newString = mystring +", "+ "'bootstrap', 'bootstrap2', 'bootstrap3'";
console.log( newString );
What about:
mystring += "'bootstrap2',";
or
var arr = ["str1", "str2", "str3"];
var mystring = arr.map((e)=>{return "'"+e+"'";}).join(",")
Array.map function used to wrap each string with single quates, than you Array.join - used to put "," between members
You can concat strings with the + operator:
var mystring = "'bootstrap'" + ",";
console.log(mystring);
Use an array and the join method.
var arr = [];
var myString = "bootstrap";
arr.push(myString);
arr.push(myString);
arr.push("other string");
arr.push("bootstrap");
// combine them with a comma or something else
console.log(arr.join(', '));
It is not suggested, but if you want to keep symbols and not care about order, and want to only add to a string beginning with 'bootstrap':
myString = "'bootstrap'";
console.log(myString.replace(/^(?='(bootstrap)')/, "'$12', '$13', "));
or you can just use capture group to keep it short
mystring.replace(/'(bootstrap)'/, "'$1', '$12', '$13'")

How to get html tag attribute values using JavaScript Regular Expressions?

Suppose I have this HTML in a string:
<meta http-equiv="Set-Cookie" content="COOKIE1_VALUE_HERE">
<meta http-equiv="Set-Cookie" content="COOKIE2_VALUE_HERE">
<meta http-equiv="Set-Cookie" content="COOKIE3_VALUE_HERE">
And I have this regular expression, to get the values inside the content attributes:
/<meta http-equiv=[\"']?set-cookie[\"']? content=[\"'](.*)[\"'].*>/ig
How do I, in JavaScript, get all three content values?
I've tried:
var setCookieMetaRegExp = /<meta http-equiv=[\"']?set-cookie[\"']? content=[\"'](.*)[\"'].*>/ig;
var match = setCookieMetaRegExp.exec(htmlstring);
but match doesn't contain the values I need. Help?
Note: the regular expression is already correct (see here). I just need to match it to the string.
Note: I'm using NodeJS
You were so close! All that needs to be done now is a simple loop:
var htmlString = '<meta http-equiv="Set-Cookie" content="COOKIE1_VALUE_HERE">\n'+
'<meta http-equiv="Set-Cookie" content="COOKIE2_VALUE_HERE">\n'+
'<meta http-equiv="Set-Cookie" content="COOKIE3_VALUE_HERE">\n';
var setCookieMetaRegExp = /<meta http-equiv=[\"']?set-cookie[\"']? content=[\"'](.*)[\"'].*>/ig;
var matches = [];
while (setCookieMetaRegExp.exec(htmlString)) {
matches.push(RegExp.$1);
}
//contains all cookie values
console.log(matches);
JSBIN: http://jsbin.com/OpepUjeW/1/edit?js,console
Keep it simple:
/content=\"(.*?)\">/gi
demo: http://regex101.com/r/dF9cD8
Update (based on your comment):
/<meta http-equiv=\"Set-Cookie\" content=\"(.*?)\">/gi
runs only on this exact string. Demo: http://regex101.com/r/pT0fC2
You really need the (.*?) with the question mark, or the regex will keep going until the last > it finds (or newline). The ? makes the search stop at the first " (you can change this to [\"'] if you want to match either single or double quote).
no need for regular expressions just do some dom work
var head = document.createElement("head");
head.innerHTML = '<meta http-equiv="Set-Cookie" content="COOKIE1_VALUE_HERE"><meta http-equiv="Set-Cookie" content="COOKIE2_VALUE_HERE"><meta http-equiv="Set-Cookie" content="COOKIE3_VALUE_HERE">';
var metaNodes = head.childNodes;
for(var i=0; i<metaNodes.length; i++){
var contentValue = metaNodes[i].attributes.getNamedItem("content").value;
}
As you are using nodejs and BlackSheep mentions using cheerio you could use their syntax if you wish to use that lib:
//Assume htmlString contains the html
var cheerio = require('cheerio'),
$ = cheerio.load(htmlString);
var values=[];
$("meta").each(function(i, elem) {
values[i] = $(this).attr("content");
});
Try this
(?:class|href)([\s='"./]+)([\w-./?=&\\#"]+)((['#\\&?=/".\w\d]+|[\w)('-."\s]+)['"]|)
example :
function getTagAttribute(tag, attribute){
var regKey = '(?:' + attribute + ')([\\s=\'"./]+)([\\w-./?=\\#"]+)(([\'#\\&?=/".\\w\\d]+|[\\w)(\'-."\\s]+)[\'"]|)'
var regExp = new RegExp(regKey,'g');
var regResult = regExp.exec(tag);
if(regResult && regResult.length>0){
var splitKey = '(?:(' + attribute + ')+(|\\s)+([=])+(|\\s|[\'"])+)|(?:([\\s\'"]+)$)'
return regResult[0].replace(new RegExp(splitKey,'g'),'');
}else{
return '';
}
}
getTagAttribute('<a href = "./test.html#bir/deneme/?k=1&v=1" class= "xyz_bir-ahmet abc">','href');'
//return "./test.html#bir/deneme/?k=1&v=1"
Live Regexp101
Live JS Script Example
try this:
var setCookieMetaRegExp = "/<meta http-equiv=[\"']?set-cookie[\"']? content=[\"'](.*)[\"'].*>/ig";
var match = stringToFindPartFrom.match(setCookieMetaRegExp);
Try this:
var myString = '<meta http-equiv="Set-Cookie" content="COOKIE2_VALUE_HERE">';
var myRegexp = /<meta http-equiv=[\"']?set-cookie[\"']? content=[\"'](.*)[\"'].*>/ig;
var match = myRegexp.exec(myString);
alert(match[1]); // should show you the part

JavaScript - text with numbers to uppercase

I have seemingly random strings in javascript
var str = "abc123aaa2";
but I need to transform the letters to uppercase
var str = "ABC123AAA2";
I can't use any library, just vanilla JS.
I tried using
str.toUpperCase();
but that returns undefined?
Can anyone help me with a speedy workaround?
It seems you are trying:
var str = 'abc123aaa2';
/* ...*/
str.toUpperCase();
/* some action on str */
That's not how it works. Strings are immutable. You need to reassign str, if you want its value be the uppercased value:
var str = "abc123aaa2";
// later
str = str.toUpperCase();
// or at once:
var str = "abc123aaa2".toUpperCase();
toUppercase method of strings in JavaScript does not mutate the original variable. So what you need to do is to reassign what toUpperCase method is returning to the str variable
var str = "abc123aaa2";
str = str.toUpperCase()

Categories

Resources