简体   繁体   中英

Javascript - Changing string to match regex

I have a text area which I'm getting the value from and want to format this using a regex expression.My regex expression requires a number first space then characters then a multiline break.

This is my string = "282 MDJSL   889 MSHS 888 MSSH";

(This string could be random each time ).

So I want to turn this string this so its formated and eventurally put into a JSObject

282 MDJSL   
889 MSHS 
888 MSSH

This is my current code:

var textValue = $('#texbox2').val().toString();
var regex = new RegExp('/^[\s\S]*[\d\s]+[a-zA-Z0-9_-]+[\n]+$/');
var str = textValue;
 if (regex.test(textValue) === true) {

  // Match found
  console.log('Regex match');

  if ((m = regex.exec(textValue)) !== null) {

   // The result can be accessed through the `m`-variable.
   m.forEach((match, groupIndex) => {
      console.log(`Found match, group ${groupIndex}: ${match}`);
   });

  }
 }

 // Match not found 
 else {
  // Not replacing it into the format i want
  str = str.replace(regex, str);
 }

thanks

You could split by whitespace and a positive lookahead of a number.

 var string = "282 MDJSL \\n\\n 889 MSHS 888 MSSH", array = string.split(/\\s+(?=\\d)/); console.log(array); 

Seems like you can get by with a simpler regex and code.

 var str = "282 MDJSL 889 MSHS 888 MSSH"; var regex = /\\d+\\s+[az]+/gi; var m; var i = 0; while ((m = regex.exec(str))) { console.log(`Found match, group ${i++}: ${m}`); } if (i === 0) { // was no match } 

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