Scribble_Scratch
Scribble_Scratch

Reputation: 403

Isolate part of string

I need to isolate the "_Back-80x80.png" portion of the following URL, and replace it using Javascript. I understand how to replace it, just need help isolating the SKU portion with regex. The only constant will be that its comes after wp-content/uploads/ and before the last / in the string.

/wp-content/uploads/SKU_Back-80x80.png

I've captured everything after wp-content/uploads/, just can't figure out how to ignore everything before the SKU.

/\/wp-content\/uploads\/.*/g

Upvotes: 2

Views: 162

Answers (2)

Aziz.G
Aziz.G

Reputation: 3721

if you want to extract anything between / and _ like SKU here is a method:

const regex = /\/\w*\_/g

const text = "/wp-content/uploads/SKU_Back-80x80.png"

console.log(text.match(regex)[0].substring(1, (text.match(regex)[0].length - 1)))

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You want to update the whole part after /wp-content/uploads/ to the next / or end of string.

Use

s = s.replace(/(\/wp-content\/uploads\/)[^\/]*/g, "$1" + new_value);

See the regex demo

Details

  • (\/wp-content\/uploads\/) - Group 1, a literal /wp-content/uploads/ substring (it is referred to using $1 replacement backreference from the replacement pattern)
  • [^\/]* - 0 or more chars other than /

If new_value may contain $, replace it with new_value.replace(/\$/g, '$$$$') in the code above (this will escape the dollar symbols correctly).

Upvotes: 1

Related Questions