Search code examples
javascriptloopsurltext

How can I iterate text from a character to another character using Javascript?


Given a url as following :

https://website.com/demo?name=helloworld&timestamp=1234567890

How can I iterate from the = sign and the & sign, resulting in helloworld in JS?

Thanks in advance. :)


Solution

  • 1) Though you don't need to iterate here. You can use slice here to get a part of a string

    const str = "https://website.com/demo?name=helloworld&timestamp=1234567890";
    const start = str.indexOf("=");
    const end = str.indexOf("&");
    
    const result = str.slice(start + 1, end);
    console.log(result);

    2) If you still want to iterate over from = and upto & then you can do

    const str = "https://website.com/demo?name=helloworld&timestamp=1234567890";
    const end = str.indexOf("&");
    
    const resultArr = [];
    for (let start = str.indexOf("=") + 1; start < end; ++start) {
      resultArr.push(str[start]);
    }
    
    console.log(resultArr.join(""));

    3) You can also use regex here

    (?<==)\w+
    

    const str = "https://website.com/demo?name=helloworld&timestamp=1234567890";
    const match = str.match(/(?<==)\w+/);
    console.log(match[0]);