-2

I have a string that has words and spaces,

var version = "One Forty Six 1.1 V2 (10 kilo / 20 kilo) (2000 - 2005)"

I want to extract

One Forty Six 1.1 V2

out of it. What is the best practice of doing it? How can i use .slice to extract what i am looking for?

Ikt
  • 97
  • 2
  • 9
  • Do you want to extract anything that's not in parenthesis? Can you show us what you've tried so far? – Sudheesh Singanamalla Mar 04 '19 at 10:42
  • I think you need a function that would be worked with several strings right? – Vu Luu Mar 04 '19 at 10:43
  • Without knowing more about what you want, it is impossible to answer. Do you want first 20 characters? Any characters not in parentheses? Anything up to and including the word "V2"? I suspect I might know which, but you need to define it, we shouldn't have to guess. – Amadan Mar 04 '19 at 10:43
  • why do you want to extract what you already have? or you want to extract something generic? – AZ_ Mar 04 '19 at 10:45
  • 1
    Possible duplicate of [How to grab substring before a specified character jQuery or JavaScript](https://stackoverflow.com/questions/9133102/how-to-grab-substring-before-a-specified-character-jquery-or-javascript) and [Read a string until a specific character appears in javascript](https://stackoverflow.com/questions/12363516) and [How to get sub string before special character?](https://stackoverflow.com/questions/54311234) – adiga Mar 04 '19 at 10:46

4 Answers4

1

You can use split on ( to get the result. split returns an array and will contain 2 substrings separated splitted on all occurrences of (. We need to get the first part of the string so we use [0] to get that.

var version = "One Forty Six 1.1 V2 (10 kilo / 20 kilo) (2000 - 2005)";
console.log(version.split('(')[0])
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

You can use .slice by slicing the string from beginning till (

var version = "One Forty Six 1.1 V2 (10 kilo / 20 kilo) (2000 - 2005)";
console.log(version.slice(0, version.indexOf("(")-1)); // -1 is for space before (
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

var version = "One Forty Six 1.1 V2 (10 kilo / 20 kilo) (2000 - 2005)";
console.log(version.substring(0, version.indexOf('(')-1));
Syed Mehtab Hassan
  • 1,297
  • 1
  • 9
  • 23
0
version.substr(0, version.indexOf('('));

This should work

Anand Trivedi
  • 123
  • 6
  • 15