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
As the forward slash (/) is special character in regular expressions, it has to be escaped with a backward slash (\).
We should double for a backslash escape a forward slash / in a regular expression. A backslash \ is used to denote character classes, e.g. \d .
Think of the forward slash as quotation marks for regular expressions. The slashes contain the expression but are not themselves part of the expression. (If you want to test for a forward slash, you have to escape it with a backwards slash.)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With