Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  186] [ 5]  / answers: 1 / hits: 48034  / 8 Years ago, thu, april 7, 2016, 12:00:00

I need to add some CSS class based on some condition using JavaScript but facing issue in case my string contains a forward slash (/). This is what my use case is



<div id=div_product-size-icon-121NM/L class=disabled></div>
<script>
var newProductCode = '121NM/L';
if( newProductCode.contains('/') ){
newProductCode = newProductCode.replace('/','///');
$('#'+'div_product-size-icon-'+newProductCode).addClass('active');
}
</script>


I have even tried newProductCode.replace('/','/'); but while running code, I am facing following error




JavaScript error: SyntaxError: unterminated string literal




I can not change HTML along with product code; the option for me is to change it in JS.



Here is a working js example: JS code


More From » jquery

 Answers
3

I have first replaced the if statement with indexOf() and changed the .replace function as .replace('/', '\/');





var newProductCode = '121NM/L';
if (newProductCode.indexOf('/') > 0) {
alert('Once you click OK, the text will disappear!!');
newProductCode = newProductCode.replace('/', '\/');
$('#' + 'div_product-size-icon-' + newProductCode).addClass('active');
}

div.active {
display: none;
}

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<div id=div_product-size-icon-121NM/L class=disabled>Some text here</div>




[#62660] Tuesday, April 5, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gerardamosy

Total Points: 600
Total Questions: 116
Total Answers: 102

Location: Ukraine
Member since Tue, May 30, 2023
1 Year ago
;