简体   繁体   中英

get value of string before and after / in javascript

suppose i have 10 localstorage like blow:

 localStorage.setItem("item01","this is a value/100"); localStorage.setItem("item02","this new is a value/110"); localStorage.setItem("item03","this is a good value/120"); localStorage.setItem("item04","this is a nice value/130"); 

I need a java script code to check if the key of for example item01 is not 0 then put the data of item01 before / to xyz and the data after / to rfv variable.

I would suppose you split the data-string along the character "/". Something like:

var lsData = localStorage.getItem("item01");
var dataArray = lsData.split("/");

if(dataArray.length === 2){
  var xyz = dataArray[0];
  var rfv = dataArray[1];
}
else{ 
  ... error-code (could not split exactly)... 
}

This is an answer to your question "get value of string before and after / in javascript". Like I stated in the comments you can split a string into an array of substrings using a delimiter.

jsfiddle

var str= "this is a value/100";
var temp=str.split("/");

var xyz = temp[0]; //->this is a value
var rfv = temp[1]; //->100

alert('xyz = '+xyz+'\nrfv = '+rfv);

this should do it...

I'm assuming you know how to get the localStorage value, so I'm just posting an example.

var a = "this is a value/100"

var b = /^(.*?)\/(\w+)/.exec(a);
var text = b[1]
var value = b[2]

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