replace some chracters in a string by javascript - javascript

How to replace "[ by [ and "] by ]in a string below:
I replace "] by ] by this code:
var str = "[{"propertyid":10000005,"title":"country"}]"
var newstr = str .replace(/\]"/g, ']')
But I do not know how to replace "[ by [?

you cannot define a string that way it will give error
if you want the string that way you can put the string between ``
var str = `"[{"propertyid":10000005,"title":"country"}]"`
but in what scenario you want to use it that way
also lets say you received string from server or file representing array of objects
like this var str = '[{"propertyid":10000005,"title":"country"}]'
you can use arr=JSON.parse(str) to to convert it to a array in memory

Related

JS turn a multi-line string into an array (each item= a line)

For example, I have:
var str = "Hello
World"
I'm expecting an array like that : array["Hello", "World"]
I looked for a method that does that but nothing, I tried to make a loop but I don't know on what I should base my loop? From my knowledge there's not a .length property for the amount of lines in a string...
Use the split function:
var str = `Hello
World`;
var splittedArray = str.split(/\r?\n/);
console.log(splittedArray)
First thing is that the input string is not valid. It should be enclosed by backtick not with a quotes and then you can replace the new line break with the space and then split it to convert into an array.
Live Demo :
var str = `Hello
World`;
const replacedStr = str.replace(/\n/g, " ")
console.log(replacedStr.split(' '));

Convert a string of array into array javascript

In my code i am reading a hidden input value which is actually a javascript array object
<input type="hidden" id="id_num" value="{{array_values}}">
But when i taking it using jquery ($('#id_num").val()) its a string of array,
"['item1','item2','item3']"
so i can not iterate it.How should i convert into javascript array object, so that i can iterate through items in the array?
You can use JSON.parse but first you need to replace all ' with " as ' are invalid delimitters in JSON strings.
var str = "['item1','item2','item3']";
str = str.replace(/'/g, '"');
var arr = JSON.parse(str);
console.log(arr);
Another approach:
Using slice and split like this:
var str = "['item1','item2','item3']";
var arr = str.slice(1, -1) // remove [ and ]
.split(',') // this could cause trouble if the strings contain commas
.map(s => s.slice(1, -1)); // remove ' and '
console.log(arr);
You can use eval command to get values from string;
eval("[0,1,2]")
will return;
[0,1,2]
more details here
Though it should be noted, if this string value comes from users, they might inject code that would cause an issue for your structure, if this string value comes only from your logic, than it is alright to utilize eval
var arr = "['item1','item2','item3']";
var res = arr.replace(/'/g, '"')
console.log(JSON.parse(res));
A possible way of solving this:
First, substr it to remove the [..]s.
Next, remove internal quotes, since we would be getting extra when we string.split
Finally, split with ,.
let mystring = "['item1','item2','item3']";
let arr = mystring.substr(1, mystring.length - 2)
.replace(/'/g, "")
.split(",")
console.log(arr)

Javascript: String of text to array of characters

I'm trying to change a huge string into the array of chars. In other languages there is .toCharArray(). I've used split to take dots, commas an spaces from the string and make string array, but I get only separated words and don't know how to make from them a char array. or how to add another regular expression to separate word? my main goal is something else, but I need this one first. thanks
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.toLowerCase();
str = str.split(/[ ,.]+/);
You can use String#replace with regex and String#split.
arrChar = str.replace(/[', ]/g,"").split('');
Demo:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
var arrChar = str.replace(/[', ]/g,"").split('');
document.body.innerHTML = '<pre>' + JSON.stringify(arrChar, 0, 4) + '</pre>';
Add character in [] which you want to remove from string.
This will do:
var strAr = str.replace(/ /g,' ').toLowerCase().split("")
First you have to replace the , and . then you can split it:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
var strarr = str.replace(/[\s,.]+/g, "").split("");
document.querySelector('pre').innerHTML = JSON.stringify(strarr, 0, 4)
<pre></pre>
var charArray[];
for(var i = 0; i < str.length; i++) {
charArray.push(str.charAt(i));
}
Alternatively, you can simply use:
var charArray = str.split("");
I'm trying to change a huge string into the array of chars.
This will do
str = str.toLowerCase().split("");
The split() method is used to split a string into an array of
substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is
split between each character.
Note: The split() method does not change the original string.
Please read the link:
http://www.w3schools.com/jsref/jsref_split.asp
You may do it like this
var coolString,
charArray,
charArrayWithoutSpecials,
output;
coolString = "If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
// does the magic, uses string as an array to slice
charArray = Array.prototype.slice.call(coolString);
// let's do this w/o specials
charArrayWithoutSpecials = Array.prototype.slice.call(coolString.replace(/[', ]/g,""))
// printing it here
output = "<b>With special chars:</b> " + JSON.stringify(charArray);
output += "<br/><br/>";
output += "<b>With special chars:</b> " + JSON.stringify(charArrayWithoutSpecials)
document.write(output);
another way would be
[].slice.call(coolString)
I guess this is what you are looking for. Ignoring all symbols and spaces and adding all characters in to an array with lower case.
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.replace(/\W/g, '').toLowerCase().split("");
alert(str);

split words,numbers from string and put it as 2D array in JavaScript

I have an string like'[[br,1,4,12],[f,3]]'. I want to split as strings and integers and put it into array like the string [['br',1,4,12],[f,3]].string maybe like '[]' or '[[cl,2]]',ect...but the words only,br,cl,fand i. How does get the array. Any idea for this problem?
Thanks
You can do conversion that you wanted by using RegEx :
Get your string
var str = '[[br,1,4,12],[f,3]]';
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
console.log(str);
//Outputs :
[["brd",1,4,12],["f",3]] // It is still just a string
If you wanted to convert it to object, you might use this :
var str = '[[br,1,4,12],[f,3]]';
function toJSObject(str){
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
return (JSON.parse(str))
}
var obj = toJSObject(str);

Change Link Into Keywords with Javascript

I wanna change the url text into a words, but have no idea to do that. Please help me.
Here's what I wanna do, example:
some-text-url.html
into
some text url
Use the split method:
var url = "some-text-url.html";
url = url.replace(".html", ""); // remove html
var words = url.split("-");
// words is now an array of the keywords
var str = "some-text-url.html";
str = str.split('.')[0].split('-').join(' ');
.split() on the . gives an Array of:
[
"some-text-url",
"html"
]
[0] gives the first string in the Array "some-text-url"
.split() on the - gives an Array of:
[
"some",
"text",
"url"
]
And .join() passing a string with a single space gives the final result:
"some text url"
Or here's another way to avoid creating an Array with .split():
var str = "some-text-url.html";
str = str.replace(/-|\.html$/g," ");
Giving you "some text url ".
Notice the space on the end. If you don't want that, add .slice(-1) after the .replace().

Categories