Home > Mobile >  Is there any possible way to join split string with the same delimeters?
Is there any possible way to join split string with the same delimeters?

Time:12-08

Is there any possible way to join split string with the same delimeters?

For example, I have a string with sentences

const str = "Edit the Expression & Text to see matches. Roll over matches or the expression for details? PCRE & JavaScript flavors of RegEx are supported! "

And I wanna split by sentences. SMth like that.

str.split(/[\.?!;] \s?/g)

Can I somehow join that string with the same delimeters?

str.split(/[\.?!;] \s?/g).map(...).join(???)

Thanks!

CodePudding user response:

You can call match to get an array of the delimiters used, then use reduce to join the array back and insert the delimiter.

const str = `const str = "Edit the Expression & Text to see matches. Roll over matches or the expression for details? PCRE & JavaScript flavors of RegEx are supported! "`
const match = str.match(/[\.?!;] \s?/g)
const result = str.split(/[\.?!;] \s?/g).map(e => e).reduce((acc, curr, i) => (acc  = curr   (match[i] || ""), acc), "")

console.log(result)

CodePudding user response:

You could split with the delimiters as group and join the string after changing each second part as desired.

const
    str = "Edit the Expression & Text to see matches. Roll over matches or the expression for details? PCRE & JavaScript flavors of RegEx are supported! ",
    result = str
        .split(/([\.?!;] \s*)/) 
        .map((s, i) => s && i % 2 === 0 ? `<stong>${s}<strong>` : s)
        .join('');

console.log(result);

CodePudding user response:

Do multiple split/joins

let str = "Edit the Expression & Text to see matches. Roll over matches or the expression for details? PCRE & JavaScript flavors of RegEx are supported!"

const delim=['.','?','!',';']

delim.forEach(d=>{
  console.log(str.split(new RegExp(`[${d}] \\s?`))) // showing what split does
  str = str.split(new RegExp(`[${d}] \\s?`)).map(s=>s).join(d)
})

  • Related