Assuming I have a string: /someFolder/anotherFolder/fileName and I want to replace all the forward slashes with a "+" then this would work:
var someString = '/someFolder/anotherFolder/fileName'
someString.split('/').join('+');
Or using regex, this would work:
var someString = '/someFolder/anotherFolder/fileName'
someString.replace(/\//g, "+");
But what would be the best approach if I want to replace the first occurence with a '+' then the second occurence with another character like say, the '-', the third with '*' and so on so that the string someString above returns:
+someFolder-anotherFolder*fileName
You can pass a function to replace():
let someString = "/someFolder/anotherFolder/file";
const repl = [ '+', '-', '*' ];
let i = 0;
console.log(someString.replace(/\//g, (match) => repl[(i++) % repl.length]));
You could use an index and a string for getting the wanted character as a closure or take an array if you have more than one character.
var someString = '/someFolder/anotherFolder/fileName'
console.log(someString.replace(/\//g, (i => _ => "+-*"[i++])(0)));
You can use reduce method by passing an arrow function as argument.
var someString = '/someFolder/anotherFolder/fileName'
someString = someString.split('/').slice(1).reduce((str, item, index) => str + "+-*"[index] + item, "");
console.log(someString);
You may chain several String#replace() method calls with a literal string as the search argument to achieve what you need:
var someString = '/someFolder/anotherFolder/fileName';
console.log(someString.replace('/', '+').replace('/', '-').replace('/', '*'));
The point here is that non-regex search argument makes it find the first occurrence only, and since you have three different replacement strings (+, - and *) it is not quite convenient/straight forward to use a regex.
Related
I have the next problem. I need to remove a part of the string before the first dot in it. I've tried to use split function:
var str = "P001.M003.PO888393";
str = str.split(".").pop();
But the result of str is "PO888393".
I need to remove only the part before the first dot. I want next result: "M003.PO888393".
Someone knows how can I do this? Thanks!
One solution that I can come up with is finding the index of the first period and then extracting the rest of the string from that index+1 using the substring method.
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.')+1);
console.log(str)
You can use split and splice function to remove the first entry and use join function to merge the other two strings again as follows:
str = str.split('.').splice(1).join('.');
Result is
M003.PO888393
var str = "P001.M003.PO888393";
str = str.split('.').splice(1).join('.');
console.log(str);
You could use a regular expression with .replace() to match everything from the start of your string up until the first dot ., and replace that with an empty string.
var str = "P001.M003.PO888393";
var res = str.replace(/^[^\.]*\./, '');
console.log(res);
Regex explanation:
^ Match the beginning of the string
[^\.]* match zero or more (*) characters that are not a . character.
\. match a . character
Using these combined matches the first characters in the string include the first ., and replaces it with an empty string ''.
calling replace on the string with regex /^\w+\./g will do it:
let re = /^\w+\./g
let result = "P001.M003.PO888393".replace(re,'')
console.log(result)
where:
\w is word character
+ means one or more times
\. literally .
many way to achieve that:
by using slice function:
let str = "P001.M003.PO888393";
str = str.slice(str.indexOf('.') + 1);
by using substring function
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.') + 1);
by using substr function
let str = "P001.M003.PO888393";
str = str.substr(str.indexOf('.') + 1);
and ...
I have this string
let str = "name1,name2/name3"
and I want to split on "," and "/", is there is a way to split it without using regexp?
this is the desire output
name1
name2
name3
Little bit of a circus but gets it done:
let str = "name1,name2/name3";
str.split("/").join(",").split(",");
Convert all the characters you want to split by to one character and do a split on top of that.
You can split first by ,, then convert to array again and split again by /
str.split(",").join("/").split("/")
Without regexp you can use this trick
str.split('/').join(',').split(',')
Use the .split() method:
const names = "name1,name2/name3".split(/[,\/]/);
You still have to use a regex literal as the token to split on, but not regex methods specifically.
Just get imaginative with String.spit().
let str = "name1,name2/name3";
let str1 = str.split(",");
let str2 = str1[1].split("/");
let result = [str1[0],str2[0],str2[1]];
console.log(result);
If you don't want to use regex you can use this function:
function split (str, seps) {
sep1 = seps.pop();
seps.forEach(sep => {
str = str.replace(sep, sep1);
})
return str.split(sep1);
}
usage:
const separators = [',', ';', '.', '|', ' '];
const myString = 'abc,def;ghi jkl';
console.log(split(myString, separators));
You can use regexp:
"name1,name2/name3".split(/,|;| |\//);
this will split by ,, ;, or /
or
"name1,name2/name3".split(/\W/)
this will split by any non alphanumeric char
I am using Javascript and currently looking for a way to match as many of my pattern's letters as possible, maintaining the original order..
For example a search pattern queued should return the march Queue/queue against the any of the following search strings:
queueTable
scheduledQueueTable
qScheduledQueueTable
As of now I've reached as far as this:
var myregex = new RegExp("([queued])", "i");
var result = myregex.exec('queueTable');
but it doesn't seem to work correctly as it highlights the single characters q,u,e,u,e and e at the end of the word Table.
Any ideas?
Generate the regex with optional non-capturing group part where regex pattern can be generate using Array#reduceRight method.
var myregex = new RegExp("queued"
.split('')
.reduceRight(function(str, s) {
return '(?:' + s + str + ')?';
}, ''), "i");
var result = myregex.exec('queueTable');
console.log(result)
The method generates regex : /(?:q(?:u(?:e(?:u(?:e(?:d?)?)?)?)?)?)?/
UPDATE : If you want to get the first longest match then use g modifier in regex and find out the largest using Array#reduce method.
var myregex = new RegExp(
"queued".split('')
.reduceRight(function(str, s) {
return '(?:' + s + str + ')?';
}, ''), "ig");
var result = 'qscheduledQueueTable'
.match(myregex)
.reduce(function(a, b) {
return a.length > b.length ? a : b;
});
console.log(result);
I think the logic would have to be something like:
Match as many of these letters as possible, in this order.
The only real answer that comes to mind is to get the match to continue if possible, but allow it to bail out. In this case...
myregex = /q(?:u(?:e(?:u(?:e(?:d|)|)|)|)|)/;
You can generate this, of course:
function matchAsMuchAsPossible(word) { // name me something sensible please!
return new RegExp(
word.split("").join("(?:")
+ (new Array(word.length).join("|)"))
);
}
You are using square brackets - which mean that it will match a single instance of any character listed inside.
There are a few ways of interpreting your intentions:
You want to match the word queue with an optional 'd' at the end:
var myregex = new RegExp("queued?", "i");
var result = myregex.exec('queueTable');
Note this can be shorter try this:
'queueTable'.match(/queued?/i);
I also removed the brackets as these were not adding anything here.
This link provides some good examples that may help you further: https://www.w3schools.com/js/js_regexp.asp
When you use [] in a regular expression, it means you want to match any of the characters inside the brackets.
Example: if I use [abc] it means "match a single character, and this character can be 'a', 'b' or 'c'"
So in your code [queued] means "match a single character, and this character can be 'q', 'u', 'e' or 'd'" - note that 'u' and 'e' appear twice so they are redundant in this case. That's why this expression matches just one single character.
If you want to match the whole string "queued", just remove the brackets. But in this case it won't match, because queueTable doesn't have 'd'. If you want 'd' to be optional, you can use queued? as already explained in previous answers.
Try something like the following :
var myregex = /queued?\B/g;
var result = myregex.exec('queueTable');
console.log(result);
I have a string of the following format:
"hello(%npm%)hi"
My goal is to split the string into three parts
a) hello
b) (%npm%)
c) hi
I am using regex as follows:
var myString = "hello(%npm%)hi".match(/[a-z]*/);
var backdtring = "hello(%npm%)hi".match(/\)[a-z]*/);
var midstring = "hello(%npm%)hi".match(/\(\%[a-z]*\%\)/);
var res = backdtring.replace(")", "");
https://jsfiddle.net/1988/ff6aupmL/
I am trying in jsfiddle , where theres an error in the line:
var res = backdtring.replace(")", "");
"backdtring.replace is not a function" .
Whats wrong in the replace function above?
Update:
Also, have I used the best practices of regular expressions ?
As it has been mentioned in the comments, you are trying to use a String#replace method on an array, see the description of the return value of String#match:
An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.
To streamline tokenization, I'd rather use .split(/(\([^()]*\))/) to get all substrings in parentheses and the substrings that remain:
var s = "hello(%npm%)hi";
var res = s.split(/(\([^()]*\))/);
console.log(res);
Details:
(\([^()]*\)) - the pattern is enclosed with capturing group so as split could return both the substrings that match and those that do not match the pattern
\( -a literal (
[^()]* - 0+ chars other than ( and )
\) - a literal ).
Let's say I have a string:
"__3_"
...which I would like to turn into:
"__###_"
basically replacing an integer with repeated occurrences of # equivalent to the integer value. How can I achieve this?
I understand that backreferences can be used with str.replace()
var str = '__3_'
str.replace(/[0-9]/g, 'x$1x'))
> '__x3x_'
And that we can use str.repeat(n) to repeat string sequences n times.
But how can I use the backreference from .replace() as the argument of .repeat()? For example, this does not work:
str.replace(/([0-9])/g,"#".repeat("$1"))
"__3_".replace(/\d/, function(match){ return "#".repeat(+match);})
if you use babel or other es6 tool it will be
"__3_".replace(/\d/, match => "#".repeat(+match))
if you need replace __11+ with "#".repeat(11) - change regexp into /\d+/
is it what you want?
According https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
str.replace(regexp|substr, newSubStr|function)
and if you use function as second param
function (replacement)
A function to be invoked to create the new substring (to put in place of the >substring received from parameter #1). The arguments supplied to this function >are described in the "Specifying a function as a parameter" section below.
Try this:
var str = "__3_";
str = str.replace(/[0-9]+/, function(x) {
return '#'.repeat(x);
});
alert(str);
Old fashioned approach:
"__3__".replace(/\d/, function (x) {
return Array(+x + 1).join('#');
});
Try this:
var str = "__3_";
str = str.replace(/[0-9]/g,function(a){
var characterToReplace= '#';
return characterToReplace.repeat(a)
});