Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping forward slash ("/") while using JavaScript to change CSS class

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

like image 286
Umesh Awasthi Avatar asked Apr 07 '16 07:04

Umesh Awasthi


People also ask

How do you escape a forward slash in JavaScript?

As the forward slash (/) is special character in regular expressions, it has to be escaped with a backward slash (\).

How do you escape a forward 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 .

What is a forward slash in JavaScript?

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.)


1 Answers

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>
like image 183
Pugazh Avatar answered Oct 18 '22 14:10

Pugazh