简体   繁体   中英

Using RegExp to substring a string at the position of a special character

Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.

I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.

...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...

But this returns an error: ReferenceError: Can't find variable: array

I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.

What am I doing wrong?

Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:

var srcMark = ['/','-'];

Additionally, test is a function so it must be called as such:

whereAt = new RegExp(srcMark.join('|')).test(str);

Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:

str.search(new RegExp(srcMark.join('|'));

Hope that helps.

You need to use the split method:

var srcMark = Array.join(['-','/'],'|');  // "-|/" or
var regEx = new RegExp(srcMark,'g');      // /-|\//g
var substring = "222-22".split(regEx)[0]  // "222"
"ABC5DEF/G".split(regEx)[0]               // "ABC5DEF"  

From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.

EDIT :

For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.

 var arr = "ABC5DEF/G"; var ans = arr.split(/[/-]/); console.log(ans[0]); arr = "ABC5DEF-15"; ans = arr.split(/[/-]/); console.log(ans[0]); // For all special characters arr = "AB7FG/H"; ans = arr.split(new RegExp(/[^a-zA-Z0-9]/)); console.log(ans[0]); 

If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \\W

  var pattern = /\\W/; var text = 'ABC5DEF/G'; var match = pattern.exec(text); var position = match.index; console.log('character: ', match[0]); console.log('position: ', position); 

You can use regex with String.split . It will look something like that:

 var result = ['ABC5DEF/G', 'ABC5DEF-15', 'ABC5DEF', 'AB7F', 'AB7FG/H' ].map((item) => item.split(/\\W+/)); console.log(result); 

That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM