This question already has answers here:
JavaScript Number Split into individual digits
(30 answers)
Closed 5 years ago.
"2+3-8*5"
2
3
8
5
how to split this string and save different variable
Here you can split your string into an array for multiple delimiters.
var strVal = "2+3-8*5";
var resp = strVal.split(/(?:\+|\-|\*)/);
console.log("Resp: " , resp);
#Gufran solution is great with regex. If you don't want to use regex you can use isNaN with loop.
var str = "2+3-8*5";
var result = [];
for (var i = 0; i < str.length; i++) {
if (!isNaN(parseInt(str.charAt(i), 10))) {
result.push(str.charAt(i));
}
}
console.log(result);
Related
This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 2 years ago.
the replace function isnt working as a thought it would. came across this piece of code. i know the replace function is to replace all punctuation marks so as to not count them as letters. but when i log a string including punctuations it counts them as well. trying to figure out why
const getLetterCount = (stringToTest) => {
const wordArray = stringToTest.split('');
let totalLetters = 0;
for (let word of wordArray) {
word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
totalLetters += word.length;
}
console.log(totalLetters);
}
getLetterCount('boy/girl?') // returns 9 ( counting punctuation as well)
String.prototype.replace()
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
You have to reassign the new value to the variable (word).
const getLetterCount = (stringToTest) => {
const wordArray = stringToTest.split('');
let totalLetters = 0;
for (let word of wordArray) {
word = word.replace(/[.,\/#!$%\^&\*;:{}=\-_` ~()]/g, "");
totalLetters += word.length;
}
console.log(totalLetters);
}
getLetterCount('boy/girl?') // returns 9 ( counting punctuation as well)
This question already has answers here:
Splitting a string into chunks by numeric or alpha character with JavaScript
(3 answers)
Closed 5 years ago.
I'd like to split strings like
'foofo21' 'bar432' 'foobar12345'
into
['foofo', '21'] ['bar', '432'] ['foobar', '12345']
Is there an easy and simple way to do this in JavaScript?
Note that the string part (for example, foofo can be in Korean instead of English).
Second solution:
var num = "'foofo21".match(/\d+/g);
// num[0] will be 21
var letr = "foofo21".match(/[a-zA-Z]+/g);
/* letr[0] will be foofo.
Now both are separated, and you can make any string as you like. */
You want a very basic regular expression, (\d+). This will match only digits.
whole_string="lasd行書繁1234"
split_string = whole_string.split(/(\d+)/)
console.log("Text:" + split_string[0] + " & Number:" + split_string[1])
Check this sample code
var inputText = "'foofo21' 'bar432' 'foobar12345'";
function processText(inputText) {
var output = [];
var json = inputText.split(' '); // Split text by spaces into array
json.forEach(function (item) { // Loop through each array item
var out = item.replace(/\'/g,''); // Remove all single quote ' from chunk
out = out.split(/(\d+)/); // Now again split the chunk by Digits into array
out = out.filter(Boolean); // With Boolean we can filter out False Boolean Values like -> false, null, 0
output.push(out);
});
return output;
}
var inputText = "'foofo21' 'bar432' 'foobar12345'";
var outputArray = processText(inputText);
console.log(outputArray); Print outputArray on console
console.log(JSON.stringify(outputArray); Convert outputArray into JSON String and print on console
This question already has answers here:
Javascript and regex: split string and keep the separator
(11 answers)
Closed 6 years ago.
I have the following string
str = "11122+3434"
I want to split it into ["11122", "+", "3434"]. There can be following delimiters +, -, /, *
I have tried the following
strArr = str.split(/[+,-,*,/]/g)
But I get
strArr = [11122, 3434]
Delimiters are things that separate data. So the .split() method is designed to remove delimiters since delimiters are not data so they are not important at all.
In your case, the thing between two values is also data. So it's not a delimiter, it's an operator (in fact, that's what it's called in mathematics).
For this you want to parse the data instead of splitting the data. The best thing for that is therefore regexp:
var result = str.match(/(\d+)([+,-,*,/])(\d+)/);
returns an array:
["11122+3434", "11122", "+", "3434"]
So your values would be result[1], result[2] and result[3].
This should help...
str = '11122+3434+12323*56767'
strArr = str.replace(/[+,-,*,/]/g, ' $& ').split(/ /g)
console.log(strArr)
Hmm, one way is to add a space as delimiter first.
// yes,it will be better to use regex for this too
str = str.replace("+", " + ");
Then split em
strArr = str.split(" ");
and it will return your array
["11122", "+", "3434"]
in bracket +-* need escape, so
strArr = str.split(/[\+\-\*/]/g)
var str = "11122+77-3434";
function getExpression(str) {
var temp = str.split('');
var part = '';
var result = []
for (var i = 0; i < temp.length; i++) {
if (temp[i].match(/\d/) && part.match(/\d/g)) {
part += temp[i];
} else {
result.push(part);
part = temp[i]
}
if (i === temp.length - 1) { //last item
result.push(part);
part = '';
}
}
return result;
}
console.log(getExpression(str))
This question already has answers here:
How do I chop/slice/trim off last character in string using Javascript?
(25 answers)
Closed 7 years ago.
am concatinating a string inside a for loop
var s="";
for(var i=1;i<=10;i++)
{
s=s+"'"+"id"+i+"',";
}
document.write(s);
Output I got is
'id1','id2','id3','id4','id5','id6','id7','id8','id9','id10',
I am trying to get the result as
'id1','id2','id3','id4','id5','id6','id7','id8','id9','id10'
How can I remove the extra , added an the end?
Fiddle
You can use a array of strings and then join the string like
var s = [];
for (var i = 1; i <= 10; i++) {
s.push("'id" + i + "'");
}
var string = s.join();
Demo: Fiddle
Use the substring method:
var s="";
for(var i=1;i<=10;i++)
{
s=s+"'"+"id"+i+"',";
}
s = s.substring(0, s.length - 1);
document.write(s);
using JavaScript String slice() method
str.slice(0,-1);
The slice() method extracts a section of a string and returns a new string
- MDN doc
This question already has answers here:
How to get the last character of a string?
(15 answers)
Closed 8 years ago.
I know there are methods to remove characters from the beginning and from the end of a string in Javascript. What I need is trim a string in such a way that only the last 4 characters remain.
For eg:
ELEPHANT -> HANT
1234567 -> 4567
String.prototype.slice will work
var str = "ELEPHANT";
console.log(str.slice(-4));
//=> HANT
For, numbers, you will have to convert to strings first
var str = (1234567).toString();
console.log(str.slice(-4));
//=> 4567
FYI .slice returns a new string, so if you want to update the value of str, you would have to
str = str.slice(-4);
Use substr method of javascript:
var str="Elephant";
var n=str.substr(-4);
alert(n);
You can use slice to do this
string.slice(start,end)
lets assume you use jQuery + javascript as well.
Lets have a label in the HTML page with id="lblTest".
<script type="text/javascript">
function myFunc() {
val lblTest = $("[id*=lblTest]");
if (lblTest) {
var str = lblTest.text();
// this is your needed functionality
alert(str.substring(str.length-4, str.length));
} else {
alert('does not exist');
}
}
</script>
Edit: so the core part is -
var str = "myString";
var output = str.substring(str.length-4, str.length);