OscarDev
OscarDev

Reputation: 977

Search word in string with javascript

I search a certain word in a string correctly in this way:

let text = jsonDesc.plain_text;

const product = 'Producto:';

const resultProduct = text.match(new RegExp(product + '\\s(\\w+)'))[1];

console.log( resultProduct ) // Mesa

But how can I search the string if sometimes the word is lowercase and other times uppercase?

I tried this:

     var product = 'Producto:';
     var productU = 'PRODUCTO:';

     var resultProduct = text.match(new RegExp(product && productUpper + '\\s(\\w+)'))[1];

And:

var resultProduct = text.match(new RegExp( '^[a-zA-Z]' + product + '\\s(\\w+)'))[1];

But dont works, error:

Uncaught (in promise) TypeError: Cannot read property '1' of null at VueComponent.getAllProducts

Upvotes: 0

Views: 79

Answers (2)

agvera
agvera

Reputation: 31

First convert all strings to lowercase, then check if the string includes the searched word

let product = 'Producto:'
let productU = 'PRODUCTO:'
let match = product.toLowerCase().includes(productU.toLowerCase())

console.log(match)

Upvotes: 0

ug_
ug_

Reputation: 11440

You can use case insensitive matching (i) as a regex flag.

new RegExp(expression, 'i');

In your case this would look like text.match(new RegExp(product + '\\s(\\w+)', 'i'))[1];

However I would recommend not just appending the product to the expression due to it possibly containing special regex characters in it. For instance right now you have a colon in there which could cause problems. If the product is fixed I would just rewrite your code to be

var product = 'Producto';
text.match(new RegExp(product + '\\:\\s(\\w+)', 'i'))[1];

Alternatively escape the text before appending it to the rest

function escapeRegex(expression) { return expression.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); }
var product = 'Producto:';
text.match(new RegExp(escapeRegex(product) + '\\s(\\w+)', 'i'))[1];

Upvotes: 1

Related Questions