Valeriane
Valeriane

Reputation: 954

regular expression with javascript language

I am working in Jquery

Is it possible to take a fragment from String variable? such as:

var text = "azerty uiop hello qsdf ghjklm wxcvbn";

I want take "hello" with 5 symboles before and after:

uiop Hello qsdf

Upvotes: 2

Views: 186

Answers (4)

mvark
mvark

Reputation: 2105

You can also extract a fragment of a string using the substring function -

var text = "azerty uiop hello qsdf ghjklm wxcvbn";
var target = text.indexOf("hello");
print(text.substring(target-5,target+10));

Upvotes: 1

Jørgen
Jørgen

Reputation: 9130

This should work:

var text = "azerty uiop hello qsdf ghjklm wxcvbn";
console.log((text.match(/.{0,5}hello.{0,5}/) || [''])[0]); // uiop hello qsdf

Upvotes: 4

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

var text = "azerty uiop hello qsdf ghjklm wxcvbn";
text.match(/.{5}hello.{5}/)[0]; // uiop hello qsdf 

Upvotes: 0

Dennis
Dennis

Reputation: 14465

Try using a regex in plain javascript:

/.{5}hello.{5}/.exec(text)

Upvotes: 0

Related Questions