0

I have a piece of code that is creating some issues with jQuery when a "+" symbol is being passed as part of a string.

Here is an example:

var ssArr = ["First/","Second /","Third+"];
if(ssArr !== null) {
  $.each(ssArr, function(ind, val){
    if(val !== ''){
      val = val.replace(/ /g, '').replace('/', '');
      console.log(val);
      $('.tstNavLi' + val).addClass('active');
    }
  });
}
ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

ul li {
  color: coral;
  text-align: center;
  font-family: "Arial", sans-serif;
  font-size: 30px;
  border: 3px solid coral;
  margin: 20px 0
}

ul li.active {
  color: blue;
  border: 3px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  
  <ul>
    <li class="tstNavLiFirst">First</li>
    <li class="tstNavLiSecond">Second</li>
    <li class="tstNavLiThird+">Third+</li>
  </ul>
  
</body>
</html>

How can I get this to work? This is part of a cms/shopping system and the "+" symbol is used quite frequently, so I cannot change the "+" for some other symbol.

Thanks all.

1 Answer 1

1

First consider are those really classes or should they be something like data-labels?

Because if they're not actually CSS classes, you can put them as data-labels and then select them with "[data-label='"+val+"']" (optionally with escaping in case ' appears in the label...)

Otherwise, you will need to escape the input string properly, which could be a hassle.

Sign up to request clarification or add additional context in comments.

6 Comments

They are real classes and used for other functionalities including css styling. Can you expand on this - Otherwise, you will need to escape the input string properly, which could be a hassle - Thank you. And what is about the "+" symbol that creates this issue?
The + symbol is not a valid character in classes because it has a specific use in applying css. Here's the relevant documentation.
@Rich Aaaa... that makes sense.
Generally speaking, you should try to keep your classes as only alphanumeric names. Some symbol characters are valid, but others require that you escape it (prepend a \ before the symbol).
It's also worth noting that there's nothing stopping you from using [data-label='tstNavLiThird+'] in your CSS too.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.