Javascript how to split string characters into variables - javascript

I am trying to split a string's characters into variables like this:
<script>
var string = "hello";
//After splitting:
var stringAt1 = "h";
var stringAt2 = "e";
var stringAt3 = "l";
var stringAt4 = "l";
var stringAt5 = "o";
</script>
Could somebody give an example of how this can be done?

String.prototype.split() function can be used for requirement.
The split() method splits a String object into an array of strings by separating the string into substrings.
Usage
var string = "hello";
var arr = string.split('');
var stringAt1 = arr[0];
alert(stringAt1)

Split according to the non-word boundary \B (which matches between two word characters or two non-word characters).
var string = "hello";
alert(string.split(/\B/))
Then assign the splitted parts to separate variables.

In ES5 there's no other way than
var splitted = "abc".split("");
var char0 = splitted[0];
var char1 = splitted[1];
etc
In ES6 it's much easier:
var [char0, char1, char2] = "abc";

Related

javascript get substring between two sets of characters

I have the following string:
var myString = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>';
how can i get with the least code the someExtraStuff.fileExt section?
should i do indexOf {{appName}} and then until the next "/> ?
You could search for the pattern {{appName}} and take all characters who are not quotes. Then take the second element of the match.
var string = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>',
substring = (string.match(/\{\{appName\}\}([^"]+)/) || [])[1]
console.log(substring);
You can do this with three methods
// 1 option
For single match
var regex = /\{\{appName\}\}([^"]+)/;
var myString = '<p class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/>';
console.log(myString.match(regex)[1]);
// 2 option
For multiple matches
var regex = /\{\{appName\}\}([^"]+)/g;
var myString = '<p class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/>';
var temp;
var resultArray = [];
while ((temp = regex.exec(myString)) != null) {
resultArray.push(temp[1]);
}
console.log(resultArray);
// 3 option For indexOf
var firstIndex= myString.indexOf("{{appName}}");
var lastIndex =firstIndex+ myString.substring(firstIndex).indexOf('"/>')
var finalString = myString.substring(firstIndex,lastIndex).replace("{{appName}}","");
console.log(finalString);

javascript to regex to just keep letters

I have tried to write the regex to remove all white spacing, special charcters, numbers from a string and just leave the letters.
For example, if I had the string
3388#accffiillnnoooorrsttttttuy I would want the following to be returned:
accffiillnnoooorrsttttttuy
I thought this would work but for some reason it doesn't appear to be doing what I expect
var letterPattern = /[a-zA-Z]+/g;
var string = string.match(letterPattern)
You probably want this:
var letterPattern = /[a-zA-Z]+/g;
var matches = '3388#accffiillnnoooorrsttttttuy'.match(letterPattern);
var string = matches[0];
Your regex is correct, the usage of match is incomplete though.
var letterPattern = /[a-zA-Z]+/g;
var matches = string.match(letterPattern);
if (matches) {
string = matches[0];
}
Use the following Regex
var string = "3388#accffiillnnoooorrsttttttuy";
string.replace(/[^a-zA-Z]/gi,'');
Check it:
<button onclick="myFunction()">Parse the String</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "3388#accffiillnnoooorrsttttttuy";
var patt1 = /[a-zA-Z]/g;
var result = str.match(patt1);
var resultString = result.join("");
document.getElementById("demo").innerHTML = resultString;
}

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));

concat variable in regexp pattern

I use this regex
str = "asd34rgr888gfd98";
var p = str.match(/\d{2}/);
alert(p[0]);
butI not understood how can use variable as quantificator, that is how write this:
var number = 2;
var p = str.match(/\d{number}/);
P.S. I see this page JavaScript regex pattern concatenate with variable
but not understood how use example from these posts, in my case.
You need to build your regex as a string and pass it to the RegExp constructor:
var regexString = '\\d{' + number + '}';
var regex = new RegExp(regexString);
var p = str.match(regex);
Notice that when building a regex via a string, you need to add some extra escape characters to escape the string as well as the regex.
var number = "2"
var p = new RegExp("\\d{" + number + "}");
This should work:
var str = "asd34rgr888gfd98";
number = 3;
p = str.match(new RegExp('\\d{' + number + '}'));
alert(p[0]);

Splitting in string in 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

Categories