Selecting a string and ignoring spaces

橙三吉。 提交于 2021-01-02 03:51:02

问题


Does anyone know how to select the text "Some words & things (lp4)" below?

I am trying to select [something] that is between two spaces \s and that has one or more + words \b in the selection

var string = '     \n       Some words & things (lp4)    ';
var regexp = /\s[\b*]\s/i;
var selection = string.match(regexp);

console.log(selection);

回答1:


It is not exactly clear to me what you are trying to achieve. So I will cover two possibilities.

1st case: remove whitespaces

If all you basically want is to remove leading and trailing whitespace characters, then trim() will be enough to do that:

var string = '     \n       Some words & things (lp4)    ';
var selection = string.trim();
console.log(selection);

This will log

Some words & things (lp4)

to the console.

2nd case: replace only the words

In this case a regular expression can be helpful indeed.

var string = '     \n       Some words & things (lp4)    ';
var regexp = /\s+(\S+(\s\S+)*)\s+/i;
var match = string.match(regexp);

if (match === null) {
  console.log('No match was found!');
} else {
  console.log('Match (words only) is: ' + match[1]);
  var replaced = string.replace(match[1], 'New replacement text');
  console.log('Replaced value: "' + replaced + '"');
}

The regular expression here is \s+(\S+(\s\S+)*)\s+. Let me break that down into pieces:

  • \s+: look for whitespace characters (\s), and allow one or more occurences (+) - that is the whitespace at the beginning
  • \S+: look for non-whitespace characters (\S), and allow zero or more occurences (+) - this is basically a single word
  • (\s\S+)*: look for a single whitespace character (\s) followed by one or more occurences (+) of non-whitespace characters (\S), and allow the whole thing zero or more times - these are basically all words after the first word
  • the outer paranthesis () are for capturing all the words in one group - this will be the first group in the match
  • \s+: look for whitespace characters (\s), and allow one or more occurences (+) - that is the whitespace at the end

Finally, the output of this code would be:

Match (words only) is: Some words & things (lp4) 
Replaced value: "     
   New replacement text    "

That is, the whitespaces will be kept in the output, as can be seen by the position of the double quotes.




回答2:


Actually, you try to remove multiples of whitespace:

var string = '     \n       Some words   & things (lp4)    ';
var regexp = /\s{2,}/gm;
console.log(string.replace(regexp, ' ').trim());


来源:https://stackoverflow.com/questions/50356946/selecting-a-string-and-ignoring-spaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!