Can Efe
Can Efe

Reputation: 15

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].

Upvotes: 0

Views: 154

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370619

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]);

Upvotes: 4

Bouraoui Al-Moez L.A
Bouraoui Al-Moez L.A

Reputation: 989

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];

Upvotes: 0

Related Questions