akpackage akpackage - 1 month ago 11
Javascript Question

Display and Replace string from parse URL

I would like to display the parsing URL and replace string '+' with inner HTML property. Up until now, I only could do it with document.write. This is my method:

var getQueryString = function ( field, url ) {
var href = url ? url : window.location.href;
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(href);
return string ? string[1] : null;
};

var myString = getQueryString('myString');


Display it inside body:

document.write(myString);


The myString current result is:

"My+name+is+chka-chka+Slim+Shady"

What I would like to achieve as the result is:
"My name is chka-chka Slim Shady"

Instead of using document.write, is there any simple way to achieve the result with innerHTML?

Gracias!

EDIT:
Thanks to Stuart I found the answer :) Here they are

Inside the
<head>


var getQueryString = function ( field, url ) {
var href = url ? url : window.location.href;
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(href);
return string ? string[1] : null;
};

function anyName()
{
var myString1 = getQueryString('your_parsedUri');
var myString2 = myString1.replace(/\+/g, " ");
document.getElementById('yourElementWithId').innerHTML = myString2;
}

window.onload = anyName;


This one in the
<body>


<h1><div id="yourElementWithId"></div></h1>

Answer Source

Depending on where you are trying to display it (in an element with a class or id) you could use:

document.querySelector('.yourElement').innerHTML = myString;

or

document.getElementById('yourElementWithId').innerHTML = myString;