如何从URL获取参数?

时间:2019-10-14 07:49:49

标签: javascript reactjs

我有这样的网址:

http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262

我需要从此页面的URL中获取名为“ codice”的参数,并将其用于查询中。我尝试使用以下代码:

render() {
  const params = new URLSearchParams(this.props.location.search);
  const codiceHash = params.get('codice');
  console.log(params.get('codice'))
  return (
   <div className={styles}> 
     <div className="notification">
       <h2>Prima Registrazione eseguita con successo</h2>
     </div>
     {this.saveEsegue(email, transactionHash , blockHash, now, "FR", codiceHash)}
   </div>      
  )
}

但是我从console.log得到的是null。 我在做什么错了?

5 个答案:

答案 0 :(得分:1)

您的URL无效。您不能拥有#,然后不能拥有两个?在里面。

您的?codice应该是&codice

这是获取鳕鱼的一种方法

const invalidHref = "http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262&somethingelse"

const codice = invalidHref.split("codice=")[1].split("&")[0];

console.log(codice)

这是在有效URL上的处理方式

const params = new URLSearchParams("http://localhost:3000/#/firstregistration?panel=4&codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262")

const codice = params.get("codice")

console.log(codice)

答案 1 :(得分:0)

URL中的参数字符串不正确,但是要从您提供的字符串中获取字符串,我将使用RegEx。

这样,codice参数在URL中的位置无关紧要(即,您可以添加更多参数而不破坏它。RegEx会选择它。)

const url = "http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262"; // window.location.href;
const codice = url.match(/(codice=)([a-zA-Z0-9]*)/)[2];
console.log(codice) // prints fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262

答案 2 :(得分:-1)

我建议您使用模块querystring来实现这一点,这是用于此目的的最高级模块之一。

示例:

console.log(this.props.location.search);
//=> '?foo=bar'

const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}

答案 3 :(得分:-1)

由于只需要一个参数,并且知道它可以容纳哪些值,因此我将使用正则表达式。

var r = /codice=([a-z0-9]+)&/g
var matches = r.exec('http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262')
console.log(matches[1])
>> fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262

答案 4 :(得分:-1)

代码段将返回

this.searchbar.android.setOnQueryTextFocusChangeListener(new android.view.View.OnFocusChangeListener({ onFocusChange:function(v : any , hasFocus:boolean){ if(hasFocus){ ... }else{ ... } } }));

codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262更改为url_string,以获取页面的当前URL

window.location.href