programing tip

자바 스크립트 문자열에 변수를 어떻게 넣습니까?

itbloger 2020. 7. 24. 07:52
반응형

자바 스크립트 문자열에 변수를 어떻게 넣습니까? (Node.js)


s = 'hello %s, how are you doing' % (my_name)

그것이 파이썬에서하는 방법입니다. javascript / node.js에서 어떻게 할 수 있습니까?


비슷한 것을 원한다면 함수를 만들 수 있습니다.

function parse(str) {
    var args = [].slice.call(arguments, 1),
        i = 0;

    return str.replace(/%s/g, () => args[i++]);
}

용법:

s = parse('hello %s, how are you doing', my_name);

이것은 단순한 예일 뿐이며 다양한 데이터 유형 (예 %i: 등) 또는 이스케이프 처리를 고려하지 않습니다 %s. 그러나 나는 그것이 당신에게 아이디어를 줄 수 있기를 바랍니다. 나는 이와 같은 기능을 제공하는 라이브러리도 있다고 확신합니다.


Node.js v4를 사용하면 ES6의 템플릿 문자열을 사용할 수 있습니다

var my_name = 'John';
var s = `hello ${my_name}, how are you doing`;
console.log(s); // prints hello John, how are you doing

문자열 `대신 백틱으로 줄 바꿈해야합니다.'


util.format이이를 수행합니다.

v0.5.3의 일부이며 다음 과 같이 사용할 수 있습니다.

var uri = util.format('http%s://%s%s', 
      (useSSL?'s':''), apiBase, path||'/');

현재 node.js >4.0문자열 조작이 크게 개선 된 ES6 표준과 더욱 호환됩니다.

대답은 원래의 질문은 간단하게 할 수 있습니다 :

var s = `hello ${my_name}, how are you doing`;
// note: tilt ` instead of single quote '

문자열이 여러 줄로 퍼질 수있는 경우 템플릿 또는 HTML / XML 프로세스를 매우 쉽게 만듭니다. 자세한 내용과 추가 기능 : 템플릿 리터럴은 mozilla.org의 문자열 리터럴 입니다.


ES6을 사용하는 경우 템플릿 리터럴을 사용해야합니다.

//you can do this
let sentence = `My name is ${ user.name }. Nice to meet you.`

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals에서 더 읽으십시오.


그렇게

s = 'hello ' + my_name + ', how are you doing'

JS에서 sprintf를 시도 하거나이 요점을 사용할 수 있습니다


String.prototypeES2015 템플릿 리터럴 을 확장 하거나 사용 하는 몇 가지 방법 .

var result = document.querySelector('#result');
// -----------------------------------------------------------------------------------
// Classic
String.prototype.format = String.prototype.format ||
  function () {
    var args = Array.prototype.slice.call(arguments);
    var replacer = function (a){return args[a.substr(1)-1];};
    return this.replace(/(\$\d+)/gm, replacer)
};
result.textContent = 
  'hello $1, $2'.format('[world]', '[how are you?]');

// ES2015#1
'use strict'
String.prototype.format2 = String.prototype.format2 ||
  function(...merge) { return this.replace(/\$\d+/g, r => merge[r.slice(1)-1]); };
result.textContent += '\nHi there $1, $2'.format2('[sir]', '[I\'m fine, thnx]');

// ES2015#2: template literal
var merge = ['[good]', '[know]'];
result.textContent += `\nOk, ${merge[0]} to ${merge[1]}`;
<pre id="result"></pre>


const format = (...args) => args.shift().replace(/%([jsd])/g, x => x === '%j' ? JSON.stringify(args.shift()) : args.shift())

const name = 'Csaba'
const formatted = format('Hi %s, today is %s and your data is %j', name, Date(), {data: {country: 'Hungary', city: 'Budapest'}})

console.log(formatted)


var user = "your name";
var s = 'hello ' + user + ', how are you doing';

If you are using node.js, console.log() takes format string as a first parameter:

 console.log('count: %d', count);

I wrote a function which solves the problem precisely.

First argument is the string that wanted to be parameterized. You should put your variables in this string like this format "%s1, %s2, ... %s12".

Other arguments are the parameters respectively for that string.

/***
 * @example parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
 * @return "my name is John and surname is Doe"
 *
 * @firstArgument {String} like "my name is %s1 and surname is %s2"
 * @otherArguments {String | Number}
 * @returns {String}
 */
const parameterizedString = (...args) => {
  const str = args[0];
  const params = args.filter((arg, index) => index !== 0);
  if (!str) return "";
  return str.replace(/%s[0-9]+/g, matchedStr => {
    const variableIndex = matchedStr.replace("%s", "") - 1;
    return params[variableIndex];
  });
}

Examples

parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
// returns "my name is John and surname is Doe"

parameterizedString("this%s1 %s2 %s3", " method", "sooo", "goood");
// returns "this method sooo goood"

If variable position changes in that string, this function supports it too without changing the function parameters.

parameterizedString("i have %s2 %s1 and %s4 %s3.", "books", 5, "pencils", "6");
// returns "i have 5 books and 6 pencils."

Here is a Multi-line String Literal example in Node.js.

> let name = 'Fred'
> tm = `Dear ${name},
... This is to inform you, ${name}, that you are
... IN VIOLATION of Penal Code 64.302-4.
... Surrender yourself IMMEDIATELY!
... THIS MEANS YOU, ${name}!!!
...
... `
'Dear Fred,\nThis is to inform you, Fred, that you are\nIN VIOLATION of Penal Code 64.302-4.\nSurrender yourself IMMEDIATELY!\nTHIS MEANS YOU, Fred!!!\n\n'
console.log(tm)
Dear Fred,
This is to inform you, Fred, that you are
IN VIOLATION of Penal Code 64.302-4.
Surrender yourself IMMEDIATELY!
THIS MEANS YOU, Fred!!!


undefined
>

참고URL : https://stackoverflow.com/questions/7790811/how-do-i-put-variables-inside-javascript-strings-node-js

반응형