简体   繁体   中英

How can I extract the Id from a string in Javascript

I'm receiving the Id (number type) and a value (string type) from the backend and I'm passing it concatenated as a whole to another component:

const id = 12;
const value = "my_string_may_include_numbers_and_spaces";

const valueToSend = `${id} ${value}`

<MyComponent propString={valueToSend} />

Is there any way to take the prop and extract both values from inside MyComponent ? id and value are separated by space but I could include anything in between, like * or % if that helps, I just haven't found a way to do it.

Thanks in advance

Many people who do this value-concatenation thing use the pipe character | . In your case the value you'd send would be 12|my_string_may_include_numbers_and_spaces .

This is convenient because

  • pipe characters don't appear in many circumstances so they're a good delimiter.
  • you can use propertyString.split('|', 2) and get an array of two strings.

You could also consider using the tab character. You type it \t in a Javascript string. This would look like so:

const delimiter = '\t'
const propertyString = [
              12, 
              "my_string_may_include_numbers_and_spaces"]
           .join(delimiter)
const array = propertyString.split(delimiter, 2)

The trouble with tab characters is that they're hard to see in console log and other debugging output.

if I may I suggest a slightly different approach... in addition to to passing down the concatenated string, I would also create an object with two properties (id and value) and then pass that down as well to another prop.

const id = 12;
const value = "my_string_may_include_numbers_and_spaces";

const valueToSend = `${id} ${value}`

<MyComponent propString={valueToSend} objProp={{id: id, value:value}}/>

or perhaps something like this:

const newObj = {
  id: 12,
  value: "my_string_may_include_numbers_and_spaces",
  valueToSend: `${this.id} ${this.value}`
}

<MyComponent prop={newObj}/>

With the ladder option, you could then destructure if needed like this:

const MyComponent = ({id, value, valueToSend})=>{
  doSomething(id);
  if( value ){
    return somethingCool( valueToSend );
  }
}

Yes, you can use ( |,|| ) or any other special characters to create string then send it to props and whenever you want to use string, try string.split() method

const id = 12;
const value = "my_string_may_include_numbers_and_spaces";

const valueToSend = `${id} || ${value}`

const result = valueToSend.split('||')

Now using

result[0] //you can get your ID
result[1] //you can get your string

Hope all well !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM