Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify string variable value befor further processing

I’m kinda tearing my hair out trying to modify the "UC" into a "UU" stored in my "url" variable.

I need to only replace the very first UC in the string, any subsequent match must be ignored

This is my code
(The commented line is what does not work sofar 🙁 )

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

document.getElementById('btn').onclick = function() {
  var val = document.getElementById('yturl').value;
  var url = "https://www.youtube.com/embed/videoseries?list=" + val;

  //var url = Str.replace('UC','UU');

  var a = document.createElement('a');
  var linkText = document.createTextNode(url);
  a.appendChild(linkText);
  a.title = "yturl";
  a.target = '_blank';
  a.href = url;
  a.style.display = 'block';
  document.body.appendChild(a);
}
<form>
  <input type="text" id="yturl" value="UCn-K7GIs62ENvdQe6ZZk9-w" />
  <input type="button" id="btn" value="ChannelPlayListURL" />
</form>

If replacing this string is to cumbersome,
"slicing" the first two charas and adding a "UU" would also work for me (but slicing didn’t work either sadly)

>Solution :

Using String.prototype.replace() with plain string arguments will only replace the first occurrence.

You should also encode any query parameters correctly for use in a URL

const baseUrl = "https://www.youtube.com/embed/videoseries";

document.getElementById("btn").addEventListener("click", (e) => {
  e.preventDefault(); // usually a good idea, especially around forms

  // Creates a map of query parameters and encodes them when stringified
  const query = new URLSearchParams({
    list: document.getElementById("yturl").value.replace("UC", "UU"),
  });

  const url = `${baseUrl}?${query}`;

  const a = document.createElement("a");
  a.title = "yturl";
  a.target = "_blank";
  a.href = url;
  a.append(url);
  a.style.display = "block";
  document.body.appendChild(a);
});
<form>
  <input type="text" id="yturl" value="UCn-K7GIs62ENvdQe6ZZk9-w" />
  <input type="button" id="btn" value="ChannelPlayListURL" />
</form>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading