1

I have the following input name:

fw_options[testgradient][background-gradient-start-color]

I need to get the last part of the name:

background-gradient-start-color

I was able to do this with this messy code:

name.replace('][','-').replace(/^[^-]*-/,'').replace(']','').replace('[','');

However, I forgot that the name can also look like this:

fw_options[header_boxstyle][background][background-gradient-start-color]

So, I ended up with the wrong string:

backgroundbackground-gradient-start-color

Can someone please simplify this for me, so that I don't have to use multiple replaces?

I need to get the last part without matching background-gradient-start-color literally, since I have multiple names that I need to find with the same regex.

2 Answers 2

2

You can extract that with a regex and a capturing group:

\[([^\]]*)\]$

See demo

The value will be in the Group 1.

var re = /\[([^\]]*)\]$/g; 
var str = 'fw_options[testgradient][background-gradient-start-color]';
    
if ((m = re.exec(str)) !== null) {
   document.getElementById("res").innerHTML = m[1];
}
<div id="res"/>

Or a non-regex way with lastIndexOf (crude, without error checking):

var str = "fw_options[testgradient][background-gradient-start-color]";
var ido = str.lastIndexOf("[");
var idc = str.lastIndexOf("]");
alert(str.substring(ido+1,idc));

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

1 Comment

My pleasure. Also, I added a non-regex method for completeness.
1

You could use other tricks as well:

var input = 'fw_options[testgradient][background-gradient-start-color]';
alert(input.replace(/\]/g, '').split(/\[/g).pop());

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.