简体   繁体   中英

Get specific word from a text

I have a text like this:

var textVar = "Hello b/3125 this is a text.";

I want to get b/3125 from this text. But b/3125 will not be exact all the time. It could be b/29152 or b/testvarxe etc. (it will always start with b/ though).

There is not a specific length too so slice is not what i am looking for.

So I want to get [random-length-text] from a text which has b/[random-length-text].

Use a regular expression to match b/ , followed by digits ( \d+ ):

 var textVar = "Hello b/3125 this is a text."; const match = textVar.match(/b\/\d+/); console.log(match[0]);

To be more general, you could match non-space characters with \S instead of \d :

 var textVar = "Hello b/3125wefwe this is a text."; const match = textVar.match(/b\/\S+/); console.log(match[0]);

Or only alphanumeric with [\da-z] , looking ahead for a space:

 var textVar = "Hello b/3125BAD$fwe b/3125GOOD this is a text."; const match = textVar.match(/b\/[\da-z]+(?= )/i); console.log(match[0]);

If your code is always the second word and there is no extra spaces you can use this method:

var textVar = "Hello b/3125 this is a text.";
var code    = textVar.split(" ")[1];

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