1

Got a "shortcode" with certain parameters and dynamic values. Need to pull these values with javascript. This is how the shortcode looks [offer-button width="500px" bg="#ff0000" color="#3366ff" padding="40px 50px" text="Come on in!" font="11px" weight="bold" style="italic"]

For example, I want to pull value of width ("500px" in this case). I've decided to pull piece of string between 'width="' and '"'. Though, I can't get rid of a feeling- there is gotta be a better way. Here is the code of my attempt

<div class="shortcode">[offer-button width="500px" bg="#ff0000" color="#3366ff" padding="40px 50px" text="Come on in!"  font="11px" weight="bold" style="italic"]</div>

var wholeshort = $(".shortcode").html();
var widthstart =  wholeshort.indexOf('width="') + 1;
var widthend = wholeshort.indexOf('"', widthstart);
var widthval = wholeshort.substring(widthstart,widthend);

With this, I get 'idth=', instead of '500px'

Not sure where I went wrong.

2 Answers 2

1

Just use a regular expression, and capture what comes between width=" and the following " in a group:

const match = $(".shortcode").html().match(/width="([^"]+)"/);
if (match) {
  console.log(match[1]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shortcode">[offer-button width="500px" bg="#ff0000" color="#3366ff" padding="40px 50px" text="Come on in!"  font="11px" weight="bold" style="italic"]</div>

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

let w = /width="(.*?)"/.exec(s)[1];

where s contains your string with data and w contains width value.

let s= $(".shortcode").html();

let w = /width="(.*?)"/.exec(s)[1];

console.log(w);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shortcode">[offer-button width="500px" bg="#ff0000" color="#3366ff" padding="40px 50px" text="Come on in!"  font="11px" weight="bold" style="italic"]</div>

1 Comment

Sweet! Exactly what I needed. Thanks! Can accept answer in 8 minutes.

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.