Reputation: 1042
I am needing to remove text within different strings.
I need a function that will make the following...
test: example1
preview: sample2
sneakpeak: model3
view: case4
...look like this:
example1
sample2
model3
case4
I have tried using the substr
and substring
functions but was not able to find a solution.
I used selected.substr(0, selected.indexOf(':'))
but all that returned to me was the text before the colon. selected
is the variable that contains the string of text.
With the strings being different lengths, it's something that cannot be hardcoded either. Any suggestions?
Upvotes: 2
Views: 1259
Reputation: 1459
You can do it with regex /[a-z]*:\s/gim
See the example snippet code below
var string = "test: example1\n\
preview: sample2\n\
sneakpeak: model3\n\
view: case4";
var replace = string.replace(/[a-z]*:\s/gim, "");
console.log(replace);
The output will be:
example1
sample2
model3
case4
Upvotes: 0
Reputation: 31682
substring
takes two parameters: the start of the cut and the end of the cut (optional).
substr
takes two parameters: the start of the cut and the length of the cut (optional).
You should use substr
with one parameter only, the start of the cut (omitting the second parameter will make substr
cut from the start index to the end):
var result = selected.substr(selected.indexOf(':'));
You may want to trim
the result to remove the spaces around result:
var result = selected.substr(selected.indexOf(':')).trim();
Upvotes: 2
Reputation: 2307
Try this:
function getNewStr(str, delimeter = ':') {
return str.substr( str.indexOf(delimeter) + 1).trim();
}
Upvotes: 0
Reputation: 5546
Use split function. split will return an array. To remove spaces use trim()
var res = "test: example1".split(':')[1].trim();
console.log(res);
Upvotes: 2