Shniper Shniper - 25 days ago 15
Javascript Question

Creating an ID with spaces

I know that you aren't supposed to create an ID with spaces and that

<div id="id one"></div>


will just create a div with id of
id
.
However a project I am doing using a json file which is set up with a bunch of data, part of the data is the name of the section the user is clicking on to retrieve more data through ajax. However the way it is set up the id for each part on the
descriptions.html
page needs to match the data in the json file.

I don't want to hyphenate it because having "Build-a-Site" display on my webpage looks just terrible.

We are not supposed to change the ajax or json set up but I'm willing to if there is no other way.

Here is the javascript file that is deciding what is placed on the page, I tried replacing
newContent += ('<a href="descriptions.html#');
with
newContent += ('<a href="descriptions.html#').replace(/-/g, "");
but that did not remove the hyphens on the page.

// NOTE: This example will not work locally in all browsers.
// Please try it out on the website for the book http://javascriptbook.com/code/c08/
// or run it on your own server.

$(function() { // When the DOM is ready

var times; // Declare global variable
$.ajax({
beforeSend: function(xhr) { // Before requesting data
if (xhr.overrideMimeType) { // If supported
xhr.overrideMimeType("application/json"); // set MIME to prevent errors
}
}
});

// FUNCTION THAT COLLECTS DATA FROM THE JSON FILE
function loadTimetable() { // Declare function
$.getJSON('data/example.json') // Try to collect JSON data
.done( function(data){ // If successful
times = data; // Store it in a variable
}).fail( function() { // If a problem: show message
$('#event').html('Sorry! We could not load the timetable at the moment');
});
}

loadTimetable(); // Call the function


// CLICK ON THE EVENT TO LOAD A TIMETABLE
$('#content').on('click', '#event a', function(e) { // User clicks on event

e.preventDefault(); // Prevent loading page
var loc = this.id.toUpperCase(); // Get value of id attr

var newContent = ''; // Build up timetable by
for (var i = 0; i < times[loc].length; i++) { // looping through events
newContent += '<li><span class="time">' + times[loc][i].time + '</span>';
newContent += ('<a href="descriptions.html#');
newContent += times[loc][i].title.replace(/ /g, '-') + '">';
newContent += times[loc][i].title + '</a></li>';
}

$('#sessions').html('<ul>' + newContent + '</ul>'); // Display times on page

$('#event a.current').removeClass('current'); // Update selected item
$(this).addClass('current');

$('#details').text(''); // Clear third column
});

// CLICK ON A SESSION TO LOAD THE DESCRIPTION
$('#content').on('click', '#sessions li a', function(e) { // Click on session
e.preventDefault(); // Prevent loading
var fragment = this.href; // Title is in href

fragment = fragment.replace('#', ' #'); // Add space after#
$('#details').load(fragment); // To load info

$('#sessions a.current').removeClass('current'); // Update selected
$(this).addClass('current');
});


// CLICK ON PRIMARY NAVIGATION
$('nav a').on('click', function(e) { // Click on nav
e.preventDefault(); // Prevent loading
var url = this.href; // Get URL to load

$('nav a.current').removeClass('current'); // Update nav
$(this).addClass('current');

$('#container').remove(); // Remove old part
$('#content').load(url + ' #container').hide().fadeIn('slow'); // Add new
});

});

Answer

You can use a regex to replace the hyphen with a space when displaying it, and then leave it alone when using it as the id.

To read about regexes (regular expressions): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

This line of code replaces the hyphen by using a regex. Adding the g after the clause tells it to replace all instances of it in the string. If you leave the g out it would only replace the first instance.

var replacedString = stringToReplace.replace(/-/g, ' ');

You will be building the html in a loop, so can use the non-replaced version as the id, but I'm not doing that part here.

**Updated to show OPs edited code:

var newContent = '';                               // Build up timetable by
for (var i = 0; i < times[loc].length; i++) {      // looping through events
  newContent += '<li><span class="time">' + times[loc][i].time + '</span>';
  newContent += '<a href="descriptions.html#';

  // You are building a link here, so you need to add the id attribute next
  newContent += ' id="' + times[loc][i].title.replace(/ /g, '-') + '" >';

  // Next would come your link text, followed by closing tags
  newContent += times[loc][i].title + '</a></li>';

}

var stringToReplace = "Build-a-Site";

document.getElementById("unreplaced").innerHTML = stringToReplace;


var replacedString = stringToReplace.replace(/-/g, ' ');


document.getElementById("replaced").innerHTML = replacedString;
<table>
  <tr>
    <td>Unreplaced: </td>
    <td><span id="unreplaced">x</span></td>
  </tr>
  <tr>
    <td>Replaced: </td>
    <td><span id="replaced">x</span></td>
  </tr>  
</table>

Comments