0

Here is a test string:

    something { some words };

I need to match all spaces (to later delete the, ie., replace them with empty character with the "str.replace()" function) between the '{' and '}' characters, in javascript. In this example, I should match the 3 spaces (one before "some", one between "some and "words", one after "words"). I have looked into several similar questions and the lookahead and lookbehind groups, but I cannot figure out how to make it.

Can you help me?

So far, I can only match the first space character: https://regex101.com/r/2KW646/2

Edit: I use a browser that does support lookahead and lookbehind.

After I delete the matched spaces, the output should be:

    something {somewords};
  • So your output would be ```something {some word};``` ? – Sajeeb Ahamed Mar 20 '20 at 18:16
  • The problem is that JavaScript's regex flavour doesn't support lookbehinds, only lookaheads. You can still hack around probably, for example with something like `[^{]+(?=})`. – sp00m Mar 20 '20 at 18:18
  • regex to capture the stuff between the curly braces first `/\{(.*)\}/`, then just use trim on the captured group and replace it. – GrahamTheDev Mar 20 '20 at 18:28
  • Search for ` (?=[^{}]*\})` and replace matches with the empty string. Sorry, I'm tired. Someone lend me a bed. ^^ – oriberu Mar 20 '20 at 19:00
  • @sp00m Javascript supports lookbehinds since the ECMAScript 2018 specification. However, not all browsers/runtimes have implemented the feature. – Zwiers Mar 20 '20 at 19:28
  • 1
    Show some examples for before and after expected results. Your question lacks clarity. And FYI regex matches in most languages tell you positions found strings begin and end. But there are normally things like string replace with regexes too. Would have to confirm with JavaScript. Yup - in JS too.. https://www.w3schools.com/jsref/jsref_replace.asp Regex 101 is great too - if you try some test string/regex combo - you can generate the javascript regex code you can then plug into your code. – JGFMK Mar 20 '20 at 19:47
  • @gjzwiers oh wow ok, good news, got to update myself! – sp00m Mar 20 '20 at 20:33
  • /(?<=\{.*)[ ]/g replace with an empty string – Poul Bak Mar 20 '20 at 20:45
  • @ArthurParmentier Does the answer meet your needs? If so do you want to accept it? Thanks. – JGFMK Mar 20 '20 at 21:08

2 Answers2

1

You might do it without regex:

const Fn = s => {
  let r = '', skip_space;
  for (let c of s) {
    if (c === '{') skip_space = !0;
    else if (c === '}') skip_space = !1;
    if (c !== ' ' || !skip_space) r += c;
  }
  return r;
}

console.log(Fn('something { some words };'))

Or with a simple replace:

const Fn = s => s.replace(
  /([^{]+)({[^}]+})/, 
  (_, m1, m2) => m1 + m2.replace(/\s+/g, '')
);

console.log(Fn('something { some words };'))
Kosh
  • 16,966
  • 2
  • 19
  • 34
0

function myFunction() {
  var str = document.getElementById("demo").innerHTML;
  var left = str.replace(/(.*?{)(.*?)(};)/, "$1");
  var mid =  str.replace(/(.*?{)(.*?)(};)/, "$2");
  var right = str.replace(/(.*?{)(.*?)(};)/, "$3");
  var midnospace = mid.split(" ").join("");
  var result = left + midnospace + right;
  document.getElementById("demo").innerHTML = result;
}
<!DOCTYPE html>
<html>
<body>
<p id="demo">something { some words };</p>
<button onclick="myFunction()">Try it</button>

</body>
</html>

A couple of related useful posts:

Explanation:

1) Split the string up into 3 capture groups. Use string replace to hold just the specific capture group numbers. The same regex is used 3 times, and the .*? makes the regex 'non-greedy', so it doesn't over expand.

a - before/including {

b - inside the {}

c - the } and after.

2) split the result from 1b) on spaces, creating a list of strings that you join back together again with an empty string to get rid of the spaces

3) recombine 1a), 2 and 1c to yield your desired answer.

JGFMK
  • 8,425
  • 4
  • 58
  • 92