javascript - split string only at one single point - Stack Overflow

I my script I need to split a string from were the dashhyphen is. And assign each piece to one variabl

I my script I need to split a string from were the dash/hyphen is. And assign each piece to one variable.

Example:

Blue Oyster Cult - Don't Fear The Reaper
Jimi Hendrix - Come On (Let The Good Times Roll)
Molly Hatchet - Dreams I'll Never See

I think regex can do it with [\-]+ but I am looking for a method that it does not make more than two variables. So whatever string it takes, the oute must be in only two pieces. I think the best approach is to consider only the first - (hyphen) in the string.

Any idea how to achieve this?

Thanks in advance.

I my script I need to split a string from were the dash/hyphen is. And assign each piece to one variable.

Example:

Blue Oyster Cult - Don't Fear The Reaper
Jimi Hendrix - Come On (Let The Good Times Roll)
Molly Hatchet - Dreams I'll Never See

I think regex can do it with [\-]+ but I am looking for a method that it does not make more than two variables. So whatever string it takes, the oute must be in only two pieces. I think the best approach is to consider only the first - (hyphen) in the string.

Any idea how to achieve this?

Thanks in advance.

Share Improve this question edited Apr 12, 2017 at 23:29 Roko C. Buljan 207k41 gold badges328 silver badges340 bronze badges asked Apr 12, 2017 at 19:36 DannyBoyDannyBoy 4441 gold badge6 silver badges23 bronze badges 5
  • 3 String.prototype.split – yBrodsky Commented Apr 12, 2017 at 19:42
  • 1 In both Java and Javascript, for Strings there is a indexOf() function which takes arguments as splitter character/string and returns array. With indexOf you can find first occurence of the '-' and hence you can get substring Example: w3schools./jsref/jsref_split.asp – Om Sao Commented Apr 12, 2017 at 19:47
  • @OmSao Thanks for you ment. The issue with split is that it makes the array of any instance of the character. So for example if there are 2 hyphen in one string, the array's length will be 3. While I am looking for a solution that it only look for the first instance and left the rest in the second item of the array. – DannyBoy Commented Apr 12, 2017 at 19:53
  • @yBrodsky, Thanks for the ment. please check the previous ment . – DannyBoy Commented Apr 12, 2017 at 19:54
  • 1 Please see the answer posted. It only breaks string at the place of first hyphen. If it's what you wanted, we can close this question by selecting the answer. – Om Sao Commented Apr 12, 2017 at 19:55
Add a ment  | 

4 Answers 4

Reset to default 6

Simply do .split(/-(.+)/)

When splitting by -(.+) the matching group (.+) will get you the needed second part in its entirety, since .+ will consume all characters after the first - till the end of line:

const text = "Hello world - This is super - easy and cool";
const parts = text.split(/-(.+)/);

console.log(parts[0].trim());      // "Hello world"
console.log(parts[1].trim());      // "This is super - easy and cool"

P.S: notice that above I use .trim() just to get rid of the string wrapping whitespaces for regex simplicity and demo!. Although, if parts[1] returns undefined, you'll get an error. So use wisely - or expand the regex to account for optional whitespaces before and after the separator - with \s?

const text = "Hello world - This is super - easy and cool";
const parts = text.split(/\s?-\s?(.+)/);

console.log(parts[0]);      // "Hello world"
console.log(parts[1]);      // "This is super - easy and cool"

Here you go!!

<script>
function myFunction() {
    var str = "Hello world-welome to the-universe wele.";
    var n = str.indexOf("-");
    var str1 = str.substring(0,str.indexOf("-"));
    var str2 = str.substring(str.indexOf("-")+1);
    document.getElementById("demo").innerHTML = str1 + "<br>" + str2;
}
</script>


<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

You could use match (with a regular expression) to turn each string into a pair (array with 2 strings):

const data = [
    "Blue Oyster Cult - Don't Fear The Reaper",
    "Jimi Hendrix - Come On (Let The Good Times Roll)",
    "Molly Hatchet - Dreams I'll Never See",
    "Gorillaz - 19 - 2000" 
];

const result = data.map( title => title.match(/(.*?)\s*-\s*(.*)/).slice(1) );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

r var string = "string - with many - hyphens";

var firstIndex = string.indexOf('-');
var result = [string.slice(0, firstIndex).trim(), string.slice(firstIndex+1).trim()]
console.log(result);

only makes a break on first - and replaces spaces at begin and end of a part with the trim function

https://jsfiddle/gLwm7Lwv/1

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744200921a4562874.html

相关推荐

  • javascript - split string only at one single point - Stack Overflow

    I my script I need to split a string from were the dashhyphen is. And assign each piece to one variabl

    8天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信