2

For Japanese language, I am trying to get Japanese added dynamically from the backend.

I want to ignore the special characters, because I am getting "

Uncaught Error: Syntax error, unrecognized expression:

Is it possible to remove -(スーペリアルーム) from superior-room-(スーペリアルーム) and get only superior-room?

I need the output to be id="superior-room".

HTML:

    <div id =superior-room-(スーペリアルーム)" class="list-item">
      <p>Title</p>
    </div>

JS:

    var message = '';
    var numAvailableRooms;
    var roomContianerId = $('.list-item').attr('id');

    if (numAvailableRooms < 100) {
      message = '50 rooms left!';
    } else {
      message = 'High demand!';
    }

    if (message == '') {
      $('#' + roomContianerId + ' .demand-message').hide();
    } else {
      $('#' + roomContianerId + ' .demand-message').show();
      $('#' + roomContianerId + ' .demand-message').html(message);
    }
Philosophist
  • 103
  • 1
  • 13
TDG
  • 1,294
  • 4
  • 18
  • 50

3 Answers3

3

Using jQuery you can update only after page load, to update you can use attr() method. First of all, get all elements with an id attribute(use has attribute selector) and use attr() method with the callback to iterate and update id.

$('[id]').attr('id', function(i, id){
    // replace all character except word char, digit and -
    // using negated character class in regex
    return id.replace(/[^\w\d-]/g, '');
});

To make it fully valid refer : Javascript regex to remove illegal characters from DOM ID.

$('[id]').attr('id', function(i, id){
    return id.replace(/^[^a-z]+|[^\w:.-]+/gi, "");
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

Using pop and split you can get new id without (スーペリアルーム) and set new id to div like below.

var  id = $('div').attr('id');
var arr = id.split("-");
//remove last element from array
var popItem = arr.pop();
//change array back to string and replace , with -
var result = arr.toString().replace(',','-');
//Give New ID for div
$('div').attr('id',result)
console.log($('div').attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id =superior-room-(スーペリアルーム)" class="list-item">
  <p>Title</p>
</div>
4b0
  • 21,981
  • 30
  • 95
  • 142
  • 1
    WOW! You made my day. I've been stuck with a similar pb for weeks. I've tried Regex solutions with no satisfactory results. And I didn't know about pop() and shift() methods. BIG THANKS – ghazal Aug 11 '23 at 11:02
0

You can use javascripts splice to split at last occurrence of the hypen (-).

var str = "superior-room-(スーペリアルーム)";
var idx = "superior-room-(スーペリアルーム)".lastIndexOf('-');
console.log(str.split('').splice(0,13).join(''));

Hope this helps.

Priyesh Diukar
  • 2,032
  • 1
  • 15
  • 19