How to add empty space at the end of string? [duplicate] - javascript

This question already has answers here:
Is there a JavaScript function that can pad a string to get to a determined length?
(43 answers)
Closed 8 months ago.
Currently, I got let str = 'prefix' which has length of 6, but I would like to add empty space at the end and update it to str = 'prefix ' with length of 7.
I have tried str.split("").push("").join("") but I get error saying join is not a function.
I have also tried str[str.length] = ' ', but this doesn't work either. What other options do I have?

You can concatenate the strings:
let str = 'prefix';
str = str + ' ';
// str === 'prefix '
or, if you want to pad any sized string to a specified length:
let str = 'prefix';
str = str.padEnd(7, " ");
// str === 'prefix '

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)

while() loop runs indefinitely; the condition won't change; .replace() doesn't work as expected [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
How do you use a variable in a regular expression?
(27 answers)
Closed 3 years ago.
I am trying to replace a letter with a white space " " inside a word using the following JS code:
let letter = document.querySelector("#letter").value.toLowerCase();
var word = "letters";
var i = word.indexOf(letter);
console.log("word[i]: " + word[i]);
while(i > -1) {
console.log(i);
word.replace(word[i], " ");
console.log("word: " + word);
i = word.indexOf(letter);
console.log(i);
}
console.log("word after: " + word);
The problem is that i stays 2 and won't change. word.replace(word[i], " "); doesn't seem to do its job.
I thought of that loop to go like this:
let's say letter is t
var i will first be 2
word.replace(word[i], " "); will replace the character at word[2] with a white space
word will become le ters
i = word.indexOf(letter); will then find the next t on 3
word.replace(word[i], " "); will replace the character at word[] with a white space
word will become le ers
now i should become -1 because there aren't anymore t in word and exit the while loop
The problem is that it doesn't work like that. The while loop is running indefinitely and i stays 2.
What is the problem ?
You can use the regex /t/g
Check snippet:
//let replace = document.querySelector("#letter").value.toLowerCase();
var replace = "t";
var re = new RegExp(replace,"g");
var original_text="letters";
var extracted_text = original_text.replace(re, ' ');
console.log(extracted_text);

How to parse what is within <xxx>? [duplicate]

This question already has answers here:
Regular Expression to find a string included between two characters while EXCLUDING the delimiters
(13 answers)
Closed 3 years ago.
Say I have strings like this:
' <xxx > '
' < xxx >'
' < xxx>'
' < xxx'
' xxx<'
' xxx'
what's the easiest way to parse what's inside the brackets?
If there is only one bracket but not the matching bracket, I can throw an error.
I figure a regex might be the easiest way?
You can use string.match(). This will check if the string is valid.
const reg = /\<(.*?)\>/;
// Returns the inner value of the string, or FALSE
const getValue = v => {
v = v.match(reg);
return v ? v[1].trim() : false;
}
// Check single value
let v1 = getValue(' < xxx>');
if (v1 !== false) {
console.log(v1);
}
// Check multiple values
const values = [' <xxx > ', ' < xxx >', ' < xxx>', ' < xxx', ' xxx<', ' xxx'];
let v2 = values.map(v => getValue(v));
console.log(v2);
This could be achieved with the regex \<\s*([^>]+)\s*\>. This would capture xxx (no spaces on either side).
"<xxx>".match(/\<\s*([^>]+)\s*\>/) // [2] = 'xxx'
"<xxx >".match(/\<\s*([^>]+)\s*\>/) // [2] = 'xxx'
"xxx<".match(/\<\s*([^>]+)\s*\>/) // null
Here, we can swipe everything from the left in our first capturing group, then add a list of our desired chars, collect them in our second capturing group:
([\s\S]*?)([a-z]+)
const regex = /([\s\S]*?)([a-z]+)/gm;
const str = ` <xxx >
< xxx >
< xxx>
< xxx
xxx<
xxx `;
const subst = `$2\n`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
RegEx
If this expression wasn't desired, it can be modified or changed in regex101.com.
RegEx Circuit
jex.im also helps to visualize the expressions.

insert variable via forEach into regex expression [duplicate]

This question already has answers here:
Use dynamic (variable) string as regex pattern in JavaScript
(8 answers)
Closed 4 years ago.
As you can see below, I'm trying to count how many times a character in string J occurs in string S. The only issue is I can't put the argument o in the forEach loop into the regex expression as shown in the console.log.
var numJewelsInStones = function(J, S) {
let jArr = J.split('');
let sArr = S.split('');
jArr.forEach(o=>{
console.log(S.replace(/[^o]/g,"").length);
})
};
numJewelsInStones("aA", "aAAbbbb");
You can create regular expression with constructor function where you pass string parameters:
new RegExp('[^' + o + ']', 'g')
Your replace logic might look like:
S.replace(new RegExp('[^' + o + ']', 'g'), '')

Split a number from a string in JavaScript [duplicate]

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

Categories