add an element "/" in particular position in string with Javascript - javascript

I want to add an element "/" within a string, but only a specific position of it, e.g. from string "20180101" to expect result like "2018/01/01".is anyone know what syntax or how to make it happen.I'm still beginner in javascript
any help would be really appreciate.

Here is one option using replace with a regex pattern:
var input = "20180419";
console.log(input.replace( new RegExp("^(\\d{4})(\\d{2})(\\d{2})", "gm"),"$1/$2/$3"));

Use substr approach to get the result:
var str = "20180101";
str = str.substr(0, str.length-4) + '/' + str.substr(4, str.length);
str = str.substr(0, str.length-2) + '/' + str.substr(7, str.length);;
console.log(str);

Another option creating an array of sub-strings with slice (note that this would work the same way with substring here), and then joining each part with a /:
let s = "20180101"
let result = [s.substring(0,4), s.substring(4,6), s.substring(6,8)].join('/')

In such cases, you may find useful to treat your string as an array of digits.
Get an array of digits from your string:
let myString = '20180101';
let myArray = myString.split('') //the '' splitter means it will just split anything
Then, add into your array of digits, the desired '/' digit in the desired positions. Refer to the splice method for more information.
myArray.splice(4,0,'/');
myArray.splice(7,0,'/');
Then, build your string:
myString = myArray.join(''); //the opposite of splitting
console.log(myString) // outputs '2018/01/01'

Related

Transform number to specific string using regex

I can't seem to get my head around javascript regex, so I need your help!
I need to transform the following:
1234567891230
Into:
urn:epc:id:sgln:12345678.9123.0
I already did it with a normal javascript algorithm (see underneath), but we need to be able to configure this transformation. I just need it for the default configuration value!
Using slice it would be:
var result = "urn:epc:id:sgln:" + myString.slice(0, 8) + "." +
myString.slice(8, 12) + "." + myString.slice(12);
If you can include an explanation in your answer I would be grateful :)
If you want to use regex for this try the following:
var regex = /(\d{8})(\d{4})/;
var splittedNumber = regex.exec("123456789123");
var result = "urn:epc:id:sgln:"+splittedNumber[1]+"."+splittedNumber[2]+".0";
console.log(result);
But I would recommend the string split you did already.
You could use a regex to capture 3 groups for 12345678, 9123 and 0 and use a word boundary \b at the begin and at the end.
Then using slice you could get all elements but leave out the first element from the array returned by match because that contains the full match that we don't need.
After that you could join the elements from the array using the dot as the separator.
\b(\d{8})(\d{4})(\d)\b
let str = "1234567891230";
let prefix = "urn:epc:id:sgln:";
console.log(prefix + str.match(/\b(\d{8})(\d{4})(\d)\b/).slice(1).join("."));

Why is JavaScript's split() method not splitting on ":"?

So to start off, a bit of context. I am pulling data from the following url: "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all" using a GET method. The data returned is a series of Pokemon names and image names in the following format.
Name1:name1.png
Name2:name2.png
...
The list is 151 items long. When I call the typeOf() method "String" is returned, so I am fairly certain it is a String I am dealing with here. What I would like to do is split the String on the delimiters of "\n" and ":".
What I would like:
Name1,name1.png,Name2,name2.png...
After some experimentation with Regex, I found that the Regex to do this was "\n|:". Using this I wrote the following line to split the String apart. I tested this Regex on https://regex101.com and it seems to work properly there.
var splitData = data.split("\n|:");
("data" is the String I receive from the url.)
But instead of splitting the String and placing the substrings into an array it doesn't do anything. (At least as far as I can see.) As such my next idea was to try replacing the characters that were giving me trouble with another character and then splitting on that new character.
data = data.replace("\n", " ");
data = data.replace("/:/g", " ");
var splitData = data.split(" ");
The first line that replaces new line characters does work, but the second line to replace the ":" does not seem to do anything. So I end up with an array that is filled with Strings that look like this.
Name1:name1.png
I can split these strings by calling their index and then splitting the substring stored within, which only confuses me more.
data = data.replace("\n", " ");
var splitData = data.split(" ");
alert(splitData[0].split(":")[1]);
The above code returns "name1.png".
Am I missing something regarding the split() method? Is my Regex wrong? Is there a better way to achieve what I am attempting to do?
Right now you are splitting on the string literal "\n|:" but to do a regex you want data.split(/[:\n]/)
The MDN page shows two ways to build a Regex:
var regex1 = /\w+/;
var regex2 = new RegExp('\\w+');
The following test script was able to work for me. I decided to use the regex in the split instead of trying to replace tokens in the string. It seemed to do the trick for me.
let testResponse = `Abra:abra.png
Aerodactyl:aerodactyl.png`;
let dataArray = testResponse.split(/\n|:/g);
let commaSeperated = dataArray.join(',');
console.log(commaSeperated);
So you can simply use regex by excluding the quotes all together.
You can look at the documentation here for regular expressions. They give the following examples:
var re = /ab+c/;
var re = new RegExp('ab+c');
See below for your expected output:
var data = `Name1:name1.png
Name2:name2.png`;
var splitData = data.split(/[\n:]/);
console.log(splitData);
//Join them by a comma to get all results
console.log(splitData.join(','));
//For some nice key value pairs, you can reduce the array into an object:
var kvps = data.split("\n").reduce((res, line) => {
var split = line.split(':');
return {
...res,
[split[0]]: split[1]
};
}, {});
console.log(kvps);
I tried and this works good.
str.split(/[:\n]/)
Here is a plunker.
plunker

RegExp to filter characters after the last dot

For example, I have a string "esolri.gbn43sh.earbnf", and I want to remove every character after the last dot(i.e. "esolri.gbn43sh"). How can I do so with regular expression?
I could of course use non-RegExp way to do it, for example:
"esolri.gbn43sh.earbnf".slice("esolri.gbn43sh.earbnf".lastIndexOf(".")+1);
But I want a regular expression.
I tried /\..*?/, but that remove the first dot instead.
I am using Javascript. Any help is much appreciated.
I would use standard js rather than regex for this one, as it will be easier for others to understand your code
var str = 'esolri.gbn43sh.earbnf'
console.log(
str.slice(str.lastIndexOf('.') + 1)
)
Pattern Matching
Match a dot followed by non-dots until the end of string
let re = /\.[^.]*$/;
Use this with String.prototype.replace to achieve the desired output
'foo.bar.baz'.replace(re, ''); // 'foo.bar'
Other choices
You may find it is more efficient to do a simple substring search for the last . and then use a string slicing method on this index.
let str = 'foo.bar.baz',
i = str.lastIndexOf('.');
if (i !== -1) // i = -1 means no match
str = str.slice(0, i); // "foo.bar"

Regex or lastIndexOf when removing last instance of a string

I couldn't apply answers to other similar questions (trying to replace the last occurrence of a string) because I am having trouble with the syntax.
I'm trying to replace the last occurrence of a string. The value of the string is stored in a variable that is passed to the .replace() method like this:
var str += some additive strings;
var del = a string that lives within str; // the value is dynamic
str = str.replace(del$, ''); // this doesn't work to remove the last occurrence of `del` in str
As I understand it the $ argument looks for the last occurrence of a string within a regex; but I can't figure out how to use it alongside a variable passed to .replace(). Any suggestions?
If you want to use the RegExp with a $, do it like this:
var str += 'some additive strings';
var re = new RegExp('a string that lives within str$');
str = str.replace(re, '');
str = str.substring(0, str.length - del.length);
You can use lastIndexOf() with slice()
Example:
var str ="HI this is cool isn't it? cool";
var del='cool';// put whatever here
var index = test.lastIndexOf(del);
var length=del.length;
if(index!=-1)
var removeStr=test.substr(index,length);
str.replace(removeStr,''); // HI this is cool isn't it?
Mate, this is just an answer. You'll need to use it according to your needs.
Updated Live demo:http://jsfiddle.net/n2Kgn/2

javascript - replace dash (hyphen) with a space

I have been looking for this for a while, and while I have found many responses for changing a space into a dash (hyphen), I haven't found any that go the other direction.
Initially I have:
var str = "This-is-a-news-item-";
I try to replace it with:
str.replace("-", ' ');
And simply display the result:
alert(str);
Right now, it doesn't do anything, so I'm not sure where to turn. I tried reversing some of the existing ones that replace the space with the dash, and that doesn't work either.
Thanks for the help.
This fixes it:
let str = "This-is-a-news-item-";
str = str.replace(/-/g, ' ');
alert(str);
There were two problems with your code:
First, String.replace() doesn’t change the string itself, it returns a changed string.
Second, if you pass a string to the replace function, it will only replace the first instance it encounters. That’s why I passed a regular expression with the g flag, for 'global', so that all instances will be replaced.
replace() returns an new string, and the original string is not modified. You need to do
str = str.replace(/-/g, ' ');
I think the problem you are facing is almost this: -
str = str.replace("-", ' ');
You need to re-assign the result of the replacement to str, to see the reflected change.
From MSDN Javascript reference: -
The result of the replace method is a copy of stringObj after the
specified replacements have been made.
To replace all the -, you would need to use /g modifier with a regex parameter: -
str = str.replace(/-/g, ' ');
var str = "This-is-a-news-item-";
while (str.contains("-")) {
str = str.replace("-", ' ');
}
alert(str);
I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.
http://jsfiddle.net/LGCYF/
In addition to the answers already given you probably want to replace all the occurrences. To do this you will need a regular expression as follows :
str = str.replace(/-/g, ' '); // Replace all '-' with ' '
Use replaceAll() in combo with trim() may meet your needs.
const str = '-This-is-a-news-item-';
console.log(str.replaceAll('-', ' ').trim());
Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.
var str = "This-is---a--news-----item----";
Then to replace all dashes with single spaces, you could do this:
var newStr = str.split('-').filter(function(item) {
item = item ? item.replace(/-/g, ''): item
return item;
}).join(' ');
Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:
item = item ? item.replace(/-/g, ''): item
The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.
Then when your string join runs on the filtered elements, you end up with this output:
"This is a news item"
Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.
if its array like
arr = ["This-is-one","This-is-two","This-is-three"];
arr.forEach((sing,index) => {
arr[index] = sing.split("-").join(" ")
});
Output will be
['This is one', 'This is two', 'This is three']

Categories

Resources