0

I have a URL that I want to link to with a few different URLSearchParams that will update a string of text within the HTML.

My URLs will be like:

example.com?code=GreenMonkey
example.com?code=PinkPanda
example.com?code=BlueCat

Then I will have some JS in the HTML:

const params = new URL('https://example.com?code=GreenMonkey').searchParams;
params.get('code');

Then I want to change a string of text within the HTML:

<div class="code">Change this text based on the 'code' param.</div>

For example:

If 'code' param = GreenMonkey > change string to "Hello world"
If 'code' param = PinkPanda > change string to "Goodbye world"
If 'code' param = BlueCat > change string to "Aloha world"

I'm stuck on how to achieve the last part. Any direction would be appreciated!

3 Answers 3

2

Set up a hashtable object using same keys as in url.

const dict = {
  GreenMonkey: "Hello world",
  PinkPanda: "Goodbye world"
}


const params = new URL('https://example.com?code=GreenMonkey').searchParams,
      key = params.get('code');
  
document.querySelector('.code').textContent = dict[key]  
<div class="code">Change this text based on the 'code' param.</div>

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

Comments

1

Create an object that contains the key-value of the code then fetch and replace it using string literal.

const params = new URL("https://example.com?code=GreenMonkey").searchParams;
const code = params.get("code");

const codeElement = document.querySelector(".code");

function changeCode(element, code) {
  const codeStringObj = {
    GreenMonkey: "Hello World",
    PinkPanda: "Goodbye world",
    BlueCat: "Aloha world"
  }

  element.textContent = `change ${codeStringObj[code]} text based on the 'code' param`;
}

changeCode(codeElement, code);
<div class="code">Change this text based on the 'code' param.</div>

Comments

0

const params = new URL("https://example.com?code=GreenMonkey").searchParams;
const code = params.get("code");
let new_text = null;

switch(code) {
  case 'GreenMonkey':
    new_text = 'Hello World';
    break;
  case 'PinkPanda':
    new_text = 'Goodbye world';
    break;
  case 'BlueCat':
    new_text = 'Aloha world';
    break;
  default:
    new_text = '';
}

document.querySelector(".code").textContent = new_text;
<div class="code">Change this text based on the 'code' param.</div>

Comments

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.