Split a number from a string in JavaScript [duplicate] - javascript

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

Related

change words at particular location in javascript string [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed last year.
var str = "Hello world";
str.charAt(2)="P"//instead of l i am assigning the value P
console.log(str)
I want to replace some Text from the string by checking some coditions but i am getting error i also tried replace function but that return nothing does no changes in the string
You need to make an array out of the string to replace by index.
The following should do the trick.
const changeChar = (str, newValue, index) => {
let splitted = str.split("");
splitted[index] = newValue;
return splitted.join("");
}
In JavaScript, strings are immutable, there are 2 ways you can do this which I have mentioned below
1 way can be to split the string using two substrings and stuff the character between them
var s = "Hello world";
var index = 2;
s = s.substring(0, index) + 'p' + s.substring(index + 1);
console.log(s)
2 way can be to convert the string to character array, replace one array member and join it
var str="Hello World"
str = str.split('');
str[2] = 'p';
str = str.join('');
console.log(str)

Remove string quotes from a array javascript? [duplicate]

This question already has answers here:
Parsing string as JSON with single quotes?
(10 answers)
Convert string into an array of arrays in javascript
(3 answers)
Closed 2 years ago.
I'm trying to remove " " from an array inside a string.
var test = "['a']"
var test1 = "['a','b']"
Expected Output:
var test_arr = ['a']
var test1_arr = ['a','b']
I tried replacing, didn't work
var test_arr = test.replace(/\"/, '');
I see two ways to accomplish that.
JSON.parse('["a","b"]') note that the values need to be in double-quotes.
"['a','b']".replace(/[['\]]/g, '').split(',') note that you need to split after replacing the unwanted chars
Both yield an array containing the original strings.
You can simply convert the single quotes inside the strings to double quotes first to convert the string to a valid JSON, and then we can use JSON.parse to get the required array like:
var test = "['a']"
var test1 = "['a','b']"
var parseStr = str => JSON.parse(str.replace(/'/g, '"'))
var test_arr = parseStr(test)
var test1_arr = parseStr(test1)
console.log(test_arr)
console.log(test1_arr)

Get everything in string after a single comma [duplicate]

This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
How can I convert a comma-separated string to an array?
(19 answers)
Closed 4 years ago.
I have some problem with my string, the variable name is accountcode. I want only part of the string. I want everything in the string which is after the first ,, excluding any extra space after the comma. For example:
accountcode = "xxxx, tes";
accountcode = "xxxx, hello";
Then I want to output like tes and hello.
I tried:
var s = 'xxxx, hello';
s = s.substring(0, s.indexOf(','));
document.write(s);
Just use split with trim.
var accountcode = "xxxx, tes";
var result= accountcode.split(',')[1].trim();
console.log(result);
You can use String.prototype.split():
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
You can use length property of the generated array as the last index to access the string item. Finally trim() the string:
var s = 'xxxx, hello';
s = s.split(',');
s = s[s.length - 1].trim();
document.write(s);
You can use string.lastIndexOf() to pull the last word out without making a new array:
let accountcode = "xxxx, hello";
let lastCommaIndex = accountcode.lastIndexOf(',')
let word = accountcode.slice(lastCommaIndex+1).trim()
console.log(word)
You can split the String on the comma.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1]);
If you don't want any leading or trailing spaces, use trim.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1].trim());
accountcode = "xxxx, hello";
let macthed=accountcode.match(/\w+$/)
if(matched){
document.write(matched[0])
}
here \w+ means any one or more charecter
and $ meand end of string
so \w+$ means get all the character upto end of the sting
so here ' ' space is not a whole character so it started after space upto $
the if statement is required because if no match found than macthed will be null , and it found it will be an array and first element will be your match

pass variable to replace function regular expression javascript [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I want to have a 'newline'-function to pass a string to it and print it on pdf. my function so far is
var array = new Array();
function newLineFunction_PDF(text) {
var arr = text.replace(/.{70}\S*\s+/g, "$&#").split(/\s+#/);
return arr;
}
array = newLineFunction_PDF('some Text');
for( var i in array) {
print(array[i]);
}
What it does is cut the text in to pieces of length-70 incl. the last word, push it into the array and print it afterwards with new lines. Now i want to pass a number to the function, like 100, so i can decide the max-length of the text per line.
So far I tried:
function newLineFunction_PDF(text, num) {
var re = new RegExp(/.{num}\S*\s+/g);
var arr = text.replace(re, "$&#").split(/\s+#/);
return arr;
}
but I dont know how and where to add escapes into the new RegExp.
The parameter of Regexp is a string:
var re = new RegExp('.{' + num + '}\S*\s+', 'g');

splitting a string based on delimiter [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I split a string, breaking at a particular character?
I have a string in following format
part1/part2
/ is the delimiter
now I want to get split the string and get part 1. How can I do it?
result = "part1/part2".split('/')
result[0] = "part1"
result[1] = "part2
split the string and get part 1
'part1/part2'.split('/')[0]
var tokens = 'part1/part2'.split('/');
var delimeter = '/';
var string = 'part1/part2';
var splitted = string.split(delimeter);
alert(splitted[0]); //alert the part1
var result = YourString.split('/');
For your example result will be an array with 2 entries: "part1" and "part2"

Categories