0

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

2 Answers 2

1

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];
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.