-4

I have this string = rgb(192, 194, 194) -10px -10px 0px; I need to get the first -10px in that string and store as a variable. That number is dynamic and will change.

Thanks for the help. Here is what I have. I'm grabbing the text-shadow of a span and need to get the -10px value which will be added to the tooltip. This is a dynamic number that will change based on where a user clicks on a slider. I just cant figureout how to parse that string to get the -10px value.

 $('.slider-track.shadow').on('click', function (e) {
        e.preventDefault();
        var currentValue = $('.editing').find('span').css('text-shadow');
        var replaceValue = currentValue.replace(/\D/g, '');

        console.log(currentValue);
        $('.tooltip-inner.shadow').text(currentValue);
    });
  • 2
    Show your efforts and problems. – DontVoteMeDown Nov 19 '14 at 19:22
  • 1
    It's quite tempting to close this as a duplicate of [Tutorials for writing a parser with Javascript](http://stackoverflow.com/questions/5874609/tutorials-for-writing-a-parser-with-javascript) – Quentin Nov 19 '14 at 19:23

4 Answers4

2

This regex should do the trick.

var str = "rgb(192, 194, 194) -10px -10px 0px;";
var m = str.match(/(.[^)][^\s]*)+\s(.*)+\s/);

if ((m instanceof Array) && m[1]) {
    console.log(m[1].trim()) // '-10px'
}
Jonathan Crowe
  • 5,793
  • 1
  • 18
  • 28
0

Here you go.

var stringToUse = "rgb(192, 194, 194) -10px -10px 0px",
start = stringToUse.lastIndexOf(')'),
end = stringToUse.indexOf('px');

stringToUse = stringToUse.substring(start +1, end).trim();

//outputs "-10"

Hope this helps.

Update from question.

var stringToUse = "rgb(192, 194, 194) 0 -10px 0px",
start = stringToUse.lastIndexOf(')') + 1,
end = stringToUse.slice(start).trim().indexOf(" ");
stringToUse = stringToUse.slice(start).trim()
stringToUse.slice(0, end)

That works better or you can use Reg Expressions like the other answer stated.

Wes Duff
  • 373
  • 2
  • 10
0

Use Regexp match. You can find more at RegExp doc

var x = "rgb(1,2,3) 0px 10px -20px"
var y = x.match(/\) ([+-]?[0-9]*px)/)
var z = x.match(/\) ([+-]?[a-z]*px)/)
console.log("original=",x,"; good match=",y,"; no match=",z)
//prints
original= rgb(1,2,3) 0px 10px -20px ; good match= [") 0px", "0px"] ; no match= null

HTH. RegExp can do a lot more for you.

Dinesh
  • 4,437
  • 5
  • 40
  • 77
0

Here's a regex example with some explanation:

var str = "rgb(192, 194, 194) -10px -10px 0px;";
var results = str.match(/.*\)\s?([^\s]*)/);

console.log(results); // ["rgb(192, 194, 194) -10px -10px 0px;", "-10px"]

To break it up:

  • *) Matches everything up until the first ")" it sees.
  • \s? Will optionally match a blank space.
  • ([^\s]*)/) Will match everything up until but excluding the next blank space it sees. This is placed within a capturing group

This online regex app here better illustrates the above.

Edgar Sanchez
  • 246
  • 1
  • 5