JS Change string format - javascript

I have a string in the following format :
One,Two,Three,Four
and I want to change its format to "One","Two","Three","Four"
I tried the following :
var items = ['One,Two,Three,Four'];
var quotedAndCommaSeparated = '"' + items + '"';
document.write(quotedAndCommaSeparated);
which adds the double quotes at the beginning and at the end of the string. I don't want to use replace because there might be values that have a comma.
Is there a way to split the initial string and return the wanted one?

Try this
items[0].replace(/^|$/g, '"').replace(/,/g,'","')

This should give you what you want. Split on the commas and then rejoin using the delimiter you are looking for.
var quotedAndCommaSeparated = '"'+items[0].split(',').join('","')+'"'

Related

add an element "/" in particular position in string with 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'

remove quotes before an array list using jquery

I have been strugling with a problem, I am using
var srlisthidden = $('#hiddenroutList').val();
srlisthidden returns an array of list but in quotes "['0015','0016']"
$.each(srlisthidden, function(i, value) {
});
But because of the double quotes on the beginning of the array,it is not allowing the list to iterate even, I tried many different options to remove the double quotes like regEx and
jQuery.parseJSON('['+srlisthidden+']'), but none of them worked, Please give me solution.
Try this out:
var x = "['0015','0016']"; // The value that you are grabbing
var sol = eval(x); // This returns the value as an array of strings.
Is this what you are trying to achieve?
You can achieve it like this as well
var to_parse = "['0015','0016']";
var array = parse.replace(/\[|]|'/g, '').split(',');
JSON requires inner quotes around strings be double-quotes escaped with a backslash; the parser doesn't play nicely with single quotes.
Clean up your string with regex:
var str = srlisthidden.replace(/\'/g, "\"")
Output: ["0015","0016"] (as a string)
Then parse as JSON:
JSON.parse(str)
Output: ["0015", "0016"] (as an array)

regex replace in javascript/jquery

I've never really used regex so this is probably a basic question, but I need to reformat a string in javascript/jquery and I think regex is the direction to go.
How can I convert this string:
\"1\",\"2\",\"\\",\"\4\"
into:
"1","2","","4"
These are both strings, so really they'd be contained in "" but I thought that may confuse things even more.
I've tried the following but it doesn't work:
var value = '\"1\",\"2\",\"\\",\"\4\"'.replace(/\"/, '"').replace(/"\//, '"');
Try:
var value = your_string.replace(/\\/g, "");
to remove all the "\"
It's a lot of escaping... Your string is:
var str = '\\"1\\",\\"2\\",\\"\\\\",\\"\\4\\"'
console.log(str.replace(/\\/g, '')) // "1","2","","4"
However, if you want only to replace \" with " use:
console.log(str.replace(/\\"/g, '"')) // "1","2","\","\4"

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']

Javascript Value Replace for Multiple Values

I am trying to replace multiple values in a string with JS replace(). The values that I want to replace include line breaks, &, #, etc... I know how to replace one value:
var string = document.getElementById('string').value.replace(\/n/g, '<br>');
However, what is the syntax to include other values. For example, how can I make the below replace functions one function?
var string = document.getElementById('string').value.replace(\/n/g, '<br>')
var string = document.getElementById('string').value.replace('&', '%26');
You could chain it simply.
var string = document.getElementById('string').value.replace(/\n/g, '<br>').replace('&', '%26');

Categories

Resources