Reputation: 3
Hi so I have a question in Javascript, is it possible to use the given array such as
["old", "great", "other", "long", "good", "last"]
and if you have a
var str = "oldgreatotherlonggoodlastfirstnewownlittle"
and print it with spaces using the array and regex?
eg.
old great other long good lastfirstnewownlittle
I'm just doing a simple web app in javascript just for practices.
Upvotes: 0
Views: 53
Reputation: 17190
You can use Array.join() on the array to generate a regular expression, and then use this one with String.replace(). In the next example I use the replacement function of replace, it provides more control to the replacement logic in some cases. But you can avoid it and go with @Barmar answer.
let arr = ["old", "great", "other", "long", "good", "last"];
var str = "oldgreatotherlonggoodlastfirstnewownlittle";
let re = new RegExp(arr.join("|"), "g");
let out = str.replace(re, (m) => m + " ");
console.log(out);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
However, note that the previous approach only works nice on some particular situations, but for example, won't work so nice for var str = "oldotherlonglastfirstnewgoodownlittlegreat";
. Then, a more generic approach would be:
let arr = ["old", "great", "other", "long", "good", "last"];
var str1 = "oldotherlonglastfirstnewgoodownlittlegreat";
var str2 = "oldgreatotherlonggoodlastfirstnewownlittle"
const separateMatches = (str, arr) =>
{
let re = new RegExp(arr.join("|"), "g");
let out = str.replace(re, (m) => ` ${m} `);
return out.replace(/\s+/g, " ").trim();
}
console.log(separateMatches(str1, arr));
console.log(separateMatches(str2, arr));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Upvotes: 3
Reputation: 780798
Turn the array into a regular expression, and add a space before each match.
var str = "oldgreatotherlonggoodlastfirstnewownlittle";
var newstr = str.replace(/old|great|other|long|good|last/g, " $&");
console.log(newstr);
str = "greatotherlonggoodlastfirstnewownlittleold";
newstr = str.replace(/old|great|other|long|good|last/g, " $&");
console.log(newstr);
In the replacement string $&
stands for whatever matched the regular expression.
Upvotes: 2
Reputation: 672
If you are looking for a way to make a regex from your array, you could do something like this:
let words = ["old", "great", "other", "long", "good", "last"];
let reg = new RegExp(words.join("|"), "g")
You can then use it with string.replace
to achieve desirable effect
Upvotes: 1