Jquery: how to get text before and after "-" with regular expression

I have a label containing text. I need to get two text elements separated by a "-" character. How to do this using regular expressions in jQuery?

+4
source share
4 answers

I would suggest using split rather than regex. You can get both elements using string.split(" - "); . This will return an array of strings with elements broken into "-".

+6
source

Why do you need regex?

 var title = "Hello - World!"; var parts = title.split(' - '); alert(parts[0] + '\n' + parts[1]); 

If I am missing something, regex is not necessary and just causes unnecessary overhead.

+3
source

Why use a regex?

fiddle reference

 var array = $('label').map(function(){ return this.innerHTML.split('-'); }).get(); 

Markup

 <label>test-test2</label> <label>test1-test3</label> 

This will result in an array of individual text elements. See Console Output in a script link.

+3
source
 var mySplitResult = $('#myLabel').val().split("-"); 

mySplitResult[0] will contain the first bit and also mySplitResult[1] will contain the second bit.

+1
source

Source: https://habr.com/ru/post/1346264/


All Articles