Splitting in string in JavaScript - javascript

How to split a string in JavaScript with the "," as seperator?

var splitString = yourstring.split(',');
See split
var str = "test,test1,test2";
var arrStr = str.split(',');
var arrLength = arrStr.length; //returns 3

Use split to split your string:
"foo,bar,baz".split(",") // returns ["foo","bar","baz"]

var expression = "h,e,l,l,o";
var tokens = expression.split("\,");
alert(tokens[0]);// will return h

Related

How to reverse value in javascript

hello I have values like this
1-10
2-3
901-321
I want to get the reverse values for example like this
10-1
3-2
321-901
I have tried this
var str = "1-18";
var newString = "";
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
But it gives me 81-1
Instead, use String.split(), Arrary.reverse() and Arrary.join():
var str = '901-321';
var strArray = str.split('-'); // ['901', '321']
var strArrayReversed = strArray.reverse(); // ['321', '901']
var result = strArrayReversed.join('-'); // '321-901'
console.log('result = ', result);
// You can do all these steps above in one go as:
var result2 = str.split('-')
.reverse()
.join('-');
console.log('result2 = ', result2);
MDN Docs:
String.prototype.split()
Array.prototype.reverse()
Array.prototype.join()
Can split on the - to create array , reverse the array and join it back into string
var str = "1-18",
newStr = str.split('-').reverse().join('-');
console.log(newStr)
a = "12-5"
console.log(a.split('-').reverse().join('-'))
You can use the split method to divide the string in two, and then use the second part before the first, like this:
var str = "1-18";
var l = str.split("-");
return l[1] + "-" + l[0];
You could replace the string by swapping the values.
var string = '901-321';
console.log(string.replace(/(.+)-(.+)/, '$2-$1'));

replace first n occurrence of a string

I have a string var with following:
var str = getDataValue();
//str value is in this format = "aVal,bVal,cVal,dVal,eVal"
Note that the value is separated by , respectively, and the val is not fixed / hardcoded.
How do I replace only the bVal everytime?
EDIT
If you use string as the regex, escape the string to prevent malicious attacks:
RegExp.escape = function(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
new RegExp(RegExp.escape(string));
var str = "aVal,bVal,cVal,dVal,eVal";
var rgx = 'bVal';
var x = 'replacement';
var res = str.replace(rgx, x);
console.log(res);
Try this
var targetValue = 'bVal';
var replaceValue = 'yourValue';
str = str.replace(targetValue , replaceValue);

Javascript regex get string before second /

var str = '#/promotionalMailer/test1';
output should be ==> #/promotionalMailer
I want the string before the second slash '/'
I have tried this so far:
var str = '#/promotionalMailer/test1';
var match = str.match(/([^\/]*\/){2}/)[0];
alert(match);
But it comes with the second slash.
try split, slice and join
var str = '#/promotionalMailer/test1';
console.log( str.split("/").slice(0,2).join("/"));
For example,
var str = '#/promotionalMailer/test1/foo/bar/baz';
result = str.split('/').slice(0, 2).join('/')
document.write('<pre>'+JSON.stringify(result,0,3));
If you want regexes, then
var str = '#/promotionalMailer/test1/foo/bar/baz';
result = str.match(/[^\/]*\/[^\/]*/)[0]
document.write('<pre>'+JSON.stringify(result,0,3));

Split and join in JavaScript?

I have a String "SHELF-2-1-1-2-1", I need to remove "2" from that string and want the output to be "SHELF-1-1-2-1"
I tried:
var str = "SHELF-2-1-1-2-1";
var res = str.split("-");
How can I join the array to get "SHELF-1-1-2-1"?
This would work:
var str = "SHELF-2-1-1".split('-2').join('');
Sounds like you want to do a replace... Try:
var res = str.replace('-2', '');
var str = "SHELF-2-1-1";
var res = str.split("-");
res.pop(res.indexOf('2'));
var newStr = res.join('-');
This should also work for your updated question, as it will only remove the first 2 from the string
let str = "Hello India";
let split_str = str.split("");
console.log(split_str);
let join_arr = split_str.join("");
console.log(join_arr);

JavaScript get character in sting after [ and before ]

I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));

Categories